Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace Homework46
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- Supermarket supermarket = new Supermarket();
- supermarket.Run();
- }
- }
- class Supermarket
- {
- private Queue<Customer> _queue;
- private List<Product> _products;
- public Supermarket()
- {
- _products = new List<Product>()
- {
- new Product("Молоко", 50),
- new Product("Кефир", 60),
- new Product("Колбаса", 300),
- new Product("Сосиски", 200),
- new Product("Сыр", 400),
- new Product("Пиво", 100),
- new Product("Сок", 80),
- new Product("Газировка", 70),
- new Product("Печенье", 150),
- new Product("Хлеб", 40),
- new Product("Йогурт", 75),
- new Product("Сметана", 90),
- new Product("Пельмени", 250)
- };
- int minimalQueueSize = 10;
- int maximalQueueSize = 50;
- Money = 0;
- _queue = new Queue<Customer>();
- int queueSize = Utility.GetRandomNumber(maximalQueueSize, minimalQueueSize);
- for (int i = 0; i < queueSize; i++)
- {
- _queue.Enqueue(new Customer(_products));
- }
- }
- public int Money { get; private set; }
- public int QueueSize => _queue.Count;
- public void Run()
- {
- const string CommandServeClient = "serve";
- const string CommandAddClientInQueue = "add";
- const string CommandShowMoney = "money";
- const string CommandExit = "exit";
- bool continueAdministering = true;
- while (continueAdministering)
- {
- Console.Clear();
- Console.WriteLine("=== Панель управления супермаркетом ===");
- Console.WriteLine($"1.Введите `{CommandServeClient}` чтобы обслужить следующего клиента (в очереди {QueueSize} человек)");
- Console.WriteLine($"2.Введите `{CommandAddClientInQueue}` чтобы добавить нового клиента в очередь");
- Console.WriteLine($"3.Введите `{CommandShowMoney}` чтобы показать состояние кассы (в кассе {Money} рублей)");
- Console.WriteLine($"4.Введите `{CommandExit}` чтобы выйти из программы");
- Console.Write("Выберите действие: ");
- string choice = Console.ReadLine();
- switch (choice)
- {
- case CommandServeClient:
- HandleServeClient();
- break;
- case CommandAddClientInQueue:
- HandleAddClient();
- break;
- case CommandShowMoney:
- HandleShowMoney();
- break;
- case CommandExit:
- Console.WriteLine("Завершение работы...");
- continueAdministering = false;
- break;
- default:
- HandleInvalidInput();
- break;
- }
- }
- }
- private void HandleServeClient()
- {
- if (QueueSize > 0)
- {
- Customer nextCustomer = GetNextCustomer();
- if (nextCustomer != null)
- {
- Console.WriteLine($"Обслуживается клиент номер {nextCustomer.Number}, у него {nextCustomer.Money} рублей.");
- ServeCustomer(nextCustomer);
- }
- else
- {
- Console.WriteLine("Произошла ошибка при получении следующего клиента.");
- }
- }
- else
- {
- Console.WriteLine("Очередь пуста!");
- }
- Utility.PressAnyKeyToContinue();
- }
- private void HandleAddClient()
- {
- AddCustomer(new Customer(_products));
- Console.WriteLine("Новый клиент добавлен в очередь.");
- Utility.PressAnyKeyToContinue();
- }
- private void HandleShowMoney()
- {
- Console.WriteLine($"В кассе {Money} рублей.");
- Utility.PressAnyKeyToContinue();
- }
- private void HandleInvalidInput()
- {
- Console.WriteLine("Некорректный ввод. Попробуйте еще раз.");
- Utility.PressAnyKeyToContinue();
- }
- private void ServeCustomer(Customer customer)
- {
- if (customer == null)
- return;
- Console.WriteLine($"Клиент номер {customer.Number}, у него {customer.Money} рублей.");
- Console.WriteLine("Корзина клиента:");
- foreach (var product in customer.Cart)
- {
- Console.WriteLine($" - {product.Name}, Цена: {product.Price} рублей");
- }
- int totalSum = customer.CalculateCartTotal();
- Console.WriteLine($"Итоговая сумма: {totalSum} рублей");
- if (customer.TryBuy(out int amountToPay))
- {
- Money += amountToPay;
- Console.WriteLine($"Клиент успешно оплатил покупки.");
- }
- else
- {
- Console.WriteLine($"Клиент не смог оплатить все товары.");
- }
- Console.WriteLine($"Клиент купил:");
- foreach (var product in customer.ShoppingBag)
- {
- Console.WriteLine($" - {product.Name}, Цена: {product.Price} рублей");
- }
- Console.WriteLine($"У клиента осталось {customer.Money} рублей.");
- }
- private Customer GetNextCustomer()
- {
- if (_queue.Count == 0)
- {
- return null;
- }
- return _queue.Dequeue();
- }
- private void AddCustomer(Customer customer)
- {
- _queue.Enqueue(customer);
- }
- }
- class Customer
- {
- private static int s_number = 0;
- private List<Product> _cart;
- private List<Product> _shoppingBag;
- public Customer(List<Product> availableProducts)
- {
- int minimalMoney = 200;
- int maximalMoney = 6000;
- Money = Utility.GetRandomNumber(maximalMoney, minimalMoney);
- Number = ++s_number;
- _cart = new List<Product>();
- _shoppingBag = new List<Product>();
- FillCart(availableProducts);
- }
- public int Money { get; private set; }
- public int Number { get; private set; }
- public List<Product> Cart => new List<Product>(_cart);
- public List<Product> ShoppingBag => new List<Product>(_shoppingBag);
- public int CalculateCartTotal()
- {
- int total = 0;
- foreach (Product product in _cart)
- {
- total += product.Price;
- }
- return total;
- }
- public bool TryBuy(out int amountToPay)
- {
- amountToPay = 0;
- int sum = CalculateCartTotal();
- if (!CanPurchase(sum))
- {
- return false;
- }
- amountToPay = sum;
- PayForProducts(sum);
- return true;
- }
- private bool CanPurchase(int sum)
- {
- if (Money < sum)
- {
- List<Product> productsToRemove = new List<Product>();
- while (Money < sum && _cart.Count > 0)
- {
- int deletedProductIndex = Utility.GetRandomNumber(_cart.Count - 1, 0);
- Product productToRemove = _cart[deletedProductIndex];
- Console.WriteLine($"У клиента недостаточно средств." +
- $" Он откладывает {productToRemove.Name} по цене {productToRemove.Price} рублей.");
- sum -= productToRemove.Price;
- productsToRemove.Add(productToRemove);
- }
- foreach (Product product in productsToRemove)
- {
- _cart.Remove(product);
- }
- if (Money < sum)
- {
- Console.WriteLine("Клиент ушел, ничего не купив.");
- _cart.Clear();
- return false;
- }
- }
- return true;
- }
- private void PayForProducts(int sum)
- {
- Money -= sum;
- Console.WriteLine($"Клиент отдает {sum} рублей под рассчет и складывает купленные продукты в пакет.");
- foreach (var product in _cart)
- {
- _shoppingBag.Add(product);
- }
- _cart.Clear();
- }
- private void FillCart(List<Product> availableProducts)
- {
- int minimalProductNumber = 2;
- int maximalProductNumber = 19;
- int productNumber = Utility.GetRandomNumber(maximalProductNumber, minimalProductNumber);
- for (int i = 0; i < productNumber; i++)
- {
- _cart.Add(availableProducts[Utility.GetRandomNumber(availableProducts.Count - 1, 0)]);
- }
- }
- }
- class Product
- {
- public Product(string name, int price)
- {
- Name = name;
- Price = price;
- }
- public int Price { get; private set; }
- public string Name { get; private set; }
- }
- public static class Utility
- {
- private static Random _random = new Random();
- public static int GetRandomNumber(int maximalNumber, int minimalNumber = 0)
- {
- if (minimalNumber > maximalNumber)
- {
- throw new ArgumentException("Минимальное число должно быть меньше максимального.");
- }
- return _random.Next(minimalNumber, maximalNumber + 1);
- }
- public static void PressAnyKeyToContinue()
- {
- Console.WriteLine("\nНажмите любую кнопку чтобы продолжить.");
- Console.ReadKey(true);
- }
- }
- }
Advertisement