Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace CSLight
- {
- class Player : GameCharacter
- {
- public Player(string name, List<Product> products, int money) : base(name, products, money) { }
- }
- class Trader : GameCharacter
- {
- public Trader(string name, List<Product> products, int money) : base(name, products, money) { }
- public void SellProduct(Product productForSale)
- {
- TryGetPaid(productForSale);
- int index = FindProductIndex(item =>
- string.Equals(item.Name, productForSale.Name, StringComparison.CurrentCultureIgnoreCase));
- Product traderProduct = GetProduct(index);
- traderProduct.TryDecreaseQuantity(productForSale.Quantity);
- if (traderProduct.Quantity <= 0)
- RemoveProductAt(index);
- Console.WriteLine($"Были куплены предметы: {productForSale.Name} {productForSale.Quantity} ед.");
- }
- }
- class Product
- {
- public string Name { get; }
- public int Price { get; }
- public int Quantity { get; private set; }
- public Product(string name, int price, int quantity)
- {
- Name = name;
- Price = price;
- Quantity = quantity;
- }
- public bool TryAddQuantity(int count)
- {
- if (count < 0 || count > 100)
- {
- Console.WriteLine("Некорректное значение количества товара");
- return false;
- }
- Quantity += count;
- return true;
- }
- public bool TryDecreaseQuantity(int count)
- {
- if (count < 0 || count > 100)
- {
- Console.WriteLine("Некорректное значение количества товара");
- return false;
- }
- if (count > Quantity)
- {
- Console.WriteLine("Недостаточно товара");
- return false;
- }
- Quantity -= count;
- return true;
- }
- }
- class GameCharacter
- {
- public string Name { get; protected set; }
- public int Money { get; private set; }
- private List<Product> _products;
- public GameCharacter(string name, List<Product> products, int money)
- {
- Name = name;
- _products = products;
- Money = money;
- }
- public Product GetProduct(int index)
- {
- if (index < 0 || index >= _products.Count)
- return null;
- return _products[index];
- }
- public int FindProductIndex(Predicate<Product> match)
- {
- return _products.FindIndex(match);
- }
- public void AddProduct(Product product)
- {
- _products.Add(product);
- }
- public void RemoveProductAt(int index)
- {
- _products.RemoveAt(index);
- }
- public bool TryGetPaid(Product productForSale)
- {
- Money += productForSale.Price * productForSale.Quantity;
- return true;
- }
- public bool TryPay(Product productToBuy)
- {
- int totalSum = productToBuy.Price * productToBuy.Quantity;
- if (totalSum > Money)
- {
- Console.WriteLine("Недостаточно средств");
- return false;
- }
- Money -= totalSum;
- return true;
- }
- public void ShowProducts()
- {
- if (_products.Count == 0)
- {
- Console.WriteLine("Инвентарь пуст");
- return;
- }
- Console.WriteLine($"{Name} показывает инвентарь:");
- foreach (var product in _products)
- Console.WriteLine($" {product.Name} по цене {product.Price} ед. в количестве {product.Quantity} шт.");
- Console.WriteLine();
- }
- }
- class Program
- {
- static void Main()
- {
- Trader[] traders = {
- new Trader("Продавец трав", new List<Product>
- {
- new Product("Ромашка", 5, 8),
- new Product("Одуванчик", 3, 12),
- new Product("Колокольчик", 8, 5),
- new Product("Подсолнух", 10, 1)
- }, 583),
- new Trader("Продавец оружия", new List<Product>
- {
- new Product("Серебряный меч", 120, 2),
- new Product("Лук", 90, 4),
- new Product("Арбалет", 180, 1),
- new Product("Пушка", 3000, 1)
- }, 735),
- new Trader("Продавец одежды", new List<Product>
- {
- new Product("Кожаные штаны", 55, 6),
- new Product("Мантия-невидимка", 100, 1),
- new Product("Стальной шлем", 45, 5),
- new Product("Ботинки", 50, 5)
- }, 642)};
- Player player = new Player("Игрок", new List<Product>
- {
- new Product("Золотой меч", 150, 1),
- new Product("Ромашка", 5, 4),
- new Product("Ботинки", 50, 1)
- }, 548);
- while (true)
- {
- Console.WriteLine("\nЧто бы вы хотели сделать?\n 1 - Посмотреть свой инвентарь\n 2 - Купить товары у продавцов");
- if (Console.ReadLine() == "1")
- {
- player.ShowProducts();
- System.Threading.Thread.Sleep(2500);
- continue;
- }
- MakeDeal(player, GetCurrentTrader(traders));
- }
- }
- private static Trader GetCurrentTrader(Trader[] traders)
- {
- Trader currentTrader;
- Console.Clear();
- Console.Write("Какой продавец вам нужен?\n 1 - Продавец трав\n 2 - Продавец оружия\n 3 - Продавец одежды\n");
- switch (Console.ReadLine())
- {
- case "1":
- currentTrader = traders[0];
- break;
- case "2":
- currentTrader = traders[1];
- break;
- case "3":
- currentTrader = traders[2];
- break;
- default:
- return null;
- }
- Console.WriteLine($"\nВас приветствует {currentTrader.Name.ToLower()}");
- currentTrader.ShowProducts();
- return currentTrader;
- }
- private static void MakeDeal(Player player, Trader trader)
- {
- Console.WriteLine($"У вас на счету {player.Money} ед. денег");
- Tuple<string, int> productInfo = GetProductInfo();
- if (productInfo == null)
- return;
- string productName = productInfo.Item1;
- int productCount = productInfo.Item2;
- Product product;
- int index = trader.FindProductIndex(item =>
- string.Equals(item.Name, productName, StringComparison.CurrentCultureIgnoreCase));
- if (index < 0)
- {
- Console.WriteLine("Данного товара у продавца нет");
- return;
- }
- product = trader.GetProduct(index);
- if (product.Quantity < productCount)
- {
- Console.WriteLine("Недостаточно товара");
- return;
- }
- product = new Product(product.Name, product.Price, productCount);
- if (player.TryPay(product))
- {
- trader.SellProduct(product);
- index = player.FindProductIndex(item =>
- string.Equals(item.Name, product.Name, StringComparison.CurrentCultureIgnoreCase));
- if (index < 0)
- player.AddProduct(product);
- else
- player.GetProduct(index).TryAddQuantity(product.Quantity);
- }
- }
- private static Tuple<string, int> GetProductInfo()
- {
- string userInput;
- string[] productInfo;
- string productName;
- int productCount;
- Console.Write("Что вам нужно и сколько? (напишите через пробел, например, \"Ромашка 2\"): ");
- userInput = Console.ReadLine();
- productInfo = userInput.Split(' ');
- if (productInfo.Length == 3 && int.TryParse(productInfo[2], out productCount))
- productName = productInfo[0] + " " + productInfo[1];
- else if (productInfo.Length == 2 && int.TryParse(productInfo[1], out productCount))
- productName = productInfo[0];
- else
- return null;
- return Tuple.Create(productName, productCount);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement