Advertisement
Vlad_Savitskiy

Traders

Apr 21st, 2020
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.21 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace CSLight
  5. {
  6.     class Player : GameCharacter
  7.     {
  8.         public Player(string name, List<Product> products, int money) : base(name, products, money) { }
  9.     }
  10.  
  11.     class Trader : GameCharacter
  12.     {
  13.         public Trader(string name, List<Product> products, int money) : base(name, products, money) { }
  14.  
  15.         public void SellProduct(Product productForSale)
  16.         {
  17.             TryGetPaid(productForSale);
  18.  
  19.             int index = FindProductIndex(item =>
  20.                 string.Equals(item.Name, productForSale.Name, StringComparison.CurrentCultureIgnoreCase));
  21.  
  22.             Product traderProduct = GetProduct(index);
  23.             traderProduct.TryDecreaseQuantity(productForSale.Quantity);
  24.  
  25.             if (traderProduct.Quantity <= 0)
  26.                 RemoveProductAt(index);
  27.  
  28.             Console.WriteLine($"Были куплены предметы: {productForSale.Name} {productForSale.Quantity} ед.");
  29.         }
  30.     }
  31.  
  32.     class Product
  33.     {
  34.         public string Name { get; }
  35.         public int Price { get; }
  36.         public int Quantity { get; private set; }
  37.  
  38.         public Product(string name, int price, int quantity)
  39.         {
  40.             Name = name;
  41.             Price = price;
  42.             Quantity = quantity;
  43.         }
  44.  
  45.         public bool TryAddQuantity(int count)
  46.         {
  47.             if (count < 0 || count > 100)
  48.             {
  49.                 Console.WriteLine("Некорректное значение количества товара");
  50.                 return false;
  51.             }
  52.  
  53.             Quantity += count;
  54.             return true;
  55.         }
  56.  
  57.         public bool TryDecreaseQuantity(int count)
  58.         {
  59.             if (count < 0 || count > 100)
  60.             {
  61.                 Console.WriteLine("Некорректное значение количества товара");
  62.                 return false;
  63.             }
  64.  
  65.             if (count > Quantity)
  66.             {
  67.                 Console.WriteLine("Недостаточно товара");
  68.                 return false;
  69.             }
  70.  
  71.             Quantity -= count;
  72.             return true;
  73.         }
  74.     }
  75.  
  76.     class GameCharacter
  77.     {
  78.         public string Name { get; protected set; }
  79.         public int Money { get; private set; }
  80.         private List<Product> _products;
  81.  
  82.         public GameCharacter(string name, List<Product> products, int money)
  83.         {
  84.             Name = name;
  85.             _products = products;
  86.             Money = money;
  87.         }
  88.  
  89.         public Product GetProduct(int index)
  90.         {
  91.             if (index < 0 || index >= _products.Count)
  92.                 return null;
  93.             return _products[index];
  94.         }
  95.  
  96.         public int FindProductIndex(Predicate<Product> match)
  97.         {
  98.             return _products.FindIndex(match);
  99.         }
  100.  
  101.         public void AddProduct(Product product)
  102.         {
  103.             _products.Add(product);
  104.         }
  105.  
  106.         public void RemoveProductAt(int index)
  107.         {
  108.             _products.RemoveAt(index);
  109.         }
  110.  
  111.         public bool TryGetPaid(Product productForSale)
  112.         {
  113.             Money += productForSale.Price * productForSale.Quantity;
  114.             return true;
  115.         }
  116.  
  117.         public bool TryPay(Product productToBuy)
  118.         {
  119.             int totalSum = productToBuy.Price * productToBuy.Quantity;
  120.  
  121.             if (totalSum > Money)
  122.             {
  123.                 Console.WriteLine("Недостаточно средств");
  124.                 return false;
  125.             }
  126.  
  127.             Money -= totalSum;
  128.             return true;
  129.         }
  130.  
  131.         public void ShowProducts()
  132.         {
  133.             if (_products.Count == 0)
  134.             {
  135.                 Console.WriteLine("Инвентарь пуст");
  136.                 return;
  137.             }
  138.  
  139.             Console.WriteLine($"{Name} показывает инвентарь:");
  140.             foreach (var product in _products)
  141.                 Console.WriteLine($"   {product.Name} по цене {product.Price} ед. в количестве {product.Quantity} шт.");
  142.             Console.WriteLine();
  143.         }
  144.     }
  145.  
  146.     class Program
  147.     {
  148.         static void Main()
  149.         {
  150.             Trader[] traders = {
  151.                 new Trader("Продавец трав", new List<Product>
  152.                 {
  153.                     new Product("Ромашка", 5, 8),
  154.                     new Product("Одуванчик", 3, 12),
  155.                     new Product("Колокольчик", 8, 5),
  156.                     new Product("Подсолнух", 10, 1)
  157.                 }, 583),
  158.                 new Trader("Продавец оружия", new List<Product>
  159.                 {
  160.                     new Product("Серебряный меч", 120, 2),
  161.                     new Product("Лук", 90, 4),
  162.                     new Product("Арбалет", 180, 1),
  163.                     new Product("Пушка", 3000, 1)
  164.                 }, 735),
  165.  
  166.                 new Trader("Продавец одежды", new List<Product>
  167.                 {
  168.                     new Product("Кожаные штаны", 55, 6),
  169.                     new Product("Мантия-невидимка", 100, 1),
  170.                     new Product("Стальной шлем", 45, 5),
  171.                     new Product("Ботинки", 50, 5)
  172.                 }, 642)};
  173.  
  174.             Player player = new Player("Игрок", new List<Product>
  175.             {
  176.                 new Product("Золотой меч", 150, 1),
  177.                 new Product("Ромашка", 5, 4),
  178.                 new Product("Ботинки", 50, 1)
  179.             }, 548);
  180.  
  181.             while (true)
  182.             {
  183.                 Console.WriteLine("\nЧто бы вы хотели сделать?\n   1 - Посмотреть свой инвентарь\n   2 - Купить товары у продавцов");
  184.                 if (Console.ReadLine() == "1")
  185.                 {
  186.                     player.ShowProducts();
  187.                     System.Threading.Thread.Sleep(2500);
  188.                     continue;
  189.                 }
  190.  
  191.                 MakeDeal(player, GetCurrentTrader(traders));
  192.             }
  193.         }
  194.  
  195.         private static Trader GetCurrentTrader(Trader[] traders)
  196.         {
  197.             Trader currentTrader;
  198.  
  199.             Console.Clear();
  200.             Console.Write("Какой продавец вам нужен?\n   1 - Продавец трав\n   2 - Продавец оружия\n   3 - Продавец одежды\n");
  201.  
  202.             switch (Console.ReadLine())
  203.             {
  204.                 case "1":
  205.                     currentTrader = traders[0];
  206.                     break;
  207.                 case "2":
  208.                     currentTrader = traders[1];
  209.                     break;
  210.                 case "3":
  211.                     currentTrader = traders[2];
  212.                     break;
  213.                 default:
  214.                     return null;
  215.             }
  216.  
  217.             Console.WriteLine($"\nВас приветствует {currentTrader.Name.ToLower()}");
  218.             currentTrader.ShowProducts();
  219.             return currentTrader;
  220.         }
  221.  
  222.         private static void MakeDeal(Player player, Trader trader)
  223.         {
  224.             Console.WriteLine($"У вас на счету {player.Money} ед. денег");
  225.  
  226.             Tuple<string, int> productInfo = GetProductInfo();
  227.             if (productInfo == null)
  228.                 return;
  229.             string productName = productInfo.Item1;
  230.             int productCount = productInfo.Item2;
  231.             Product product;
  232.  
  233.             int index = trader.FindProductIndex(item =>
  234.                 string.Equals(item.Name, productName, StringComparison.CurrentCultureIgnoreCase));
  235.             if (index < 0)
  236.             {
  237.                 Console.WriteLine("Данного товара у продавца нет");
  238.                 return;
  239.             }
  240.  
  241.             product = trader.GetProduct(index);
  242.             if (product.Quantity < productCount)
  243.             {
  244.                 Console.WriteLine("Недостаточно товара");
  245.                 return;
  246.             }
  247.  
  248.             product = new Product(product.Name, product.Price, productCount);
  249.             if (player.TryPay(product))
  250.             {
  251.                 trader.SellProduct(product);
  252.                
  253.                 index = player.FindProductIndex(item =>
  254.                     string.Equals(item.Name, product.Name, StringComparison.CurrentCultureIgnoreCase));
  255.                 if (index < 0)
  256.                     player.AddProduct(product);
  257.                 else
  258.                     player.GetProduct(index).TryAddQuantity(product.Quantity);
  259.             }
  260.         }
  261.  
  262.         private static Tuple<string, int> GetProductInfo()
  263.         {
  264.             string userInput;
  265.             string[] productInfo;
  266.             string productName;
  267.             int productCount;
  268.  
  269.             Console.Write("Что вам нужно и сколько? (напишите через пробел, например, \"Ромашка 2\"): ");
  270.             userInput = Console.ReadLine();
  271.  
  272.             productInfo = userInput.Split(' ');
  273.             if (productInfo.Length == 3 && int.TryParse(productInfo[2], out productCount))
  274.                 productName = productInfo[0] + " " + productInfo[1];
  275.             else if (productInfo.Length == 2 && int.TryParse(productInfo[1], out productCount))
  276.                 productName = productInfo[0];
  277.             else
  278.                 return null;
  279.  
  280.             return Tuple.Create(productName, productCount);
  281.         }
  282.     }
  283. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement