Files
cruiseSimulator/Assets/Soundings/Runtime/Company.cs

518 lines
24 KiB
C#

using System;
using System.Collections.Generic;
namespace Soundings
{
[Serializable]
public sealed class Deck
{
public Facility[] Cells;
public Deck(int size) => Cells = new Facility[size];
public int AnchorAt(int cell, int columns)
{
int rowStart = cell - cell % columns;
while (cell > rowStart && Cells[cell] == Facility.Extension)
cell--;
return cell;
}
public Facility FacilityAt(int cell, int columns) => Cells[AnchorAt(cell, columns)];
internal bool HasValidFootprints(int columns, int hull)
{
for (int anchor = 0; anchor < Cells.Length;)
{
Facility facility = Cells[anchor];
if ((uint)facility >= (uint)Facility.Extension)
return false;
FacilitySpec spec = Market.Facilities[(int)facility];
if (columns - anchor % columns < spec.Length || hull < spec.MinimumHull)
return false;
for (int offset = 1; offset < spec.Length; offset++)
if (Cells[anchor + offset] != Facility.Extension)
return false;
anchor += spec.Length;
}
return true;
}
}
[Serializable]
public sealed class Ship
{
public string Name;
public int HullIndex, Port, Condition, Fare, Fuel;
public int[] ServicePrices;
public double FuelValue;
public List<Deck> Decks = new List<Deck>();
public CruiseItinerary Itinerary;
public HullSpec Hull => Market.Hulls[HullIndex];
public int Beds => FacilityCapacity(Facility.Cabin) + SuiteBerths;
public int SuiteBerths => FacilityCapacity(Facility.Suite) + FacilityCapacity(Facility.GrandSuite);
internal int GrandSuiteBerths => FacilityCapacity(Facility.GrandSuite);
public int Meals => (FacilityCapacity(Facility.Dining) + FacilityCapacity(Facility.Restaurant)) * 3;
public int Entertainment => FacilityCapacity(Facility.Entertainment) + FacilityCapacity(Facility.GrandTheater);
public int PoolCapacity => FacilityCapacity(Facility.Amenity) + FacilityCapacity(Facility.ResortPool);
public int BarCapacity => FacilityCapacity(Facility.Bar) + FacilityCapacity(Facility.CocktailLounge);
public int Capacity => Math.Min(Beds, Meals);
public int GalleyCapacity => 168 + HullIndex * 72 + FacilityCapacity(Facility.Galley);
public int FoodCapacity => 1500 + HullIndex * 640 + FacilityCapacity(Facility.Stores);
public int WaterCapacity => 16000 + HullIndex * 7600 + FacilityCapacity(Facility.Water);
public int WaterProduction => 9000 + HullIndex * 3900 + Count(Facility.Water) * 6000;
public int WasteCapacity => 12000 + HullIndex * 6800 + FacilityCapacity(Facility.Waste);
public int WasteTreatment => 5500 + HullIndex * 3400 + Count(Facility.Waste) * 7000;
public int Tank => Hull.Tank + FacilityCapacity(Facility.Tank);
public double BurnPerMile => Hull.TonsPerMile * (1 + (100 - Condition) * .003);
public int SafeRange => Math.Max(0, (int)Math.Floor(Math.Min(Fuel - 6, Fuel * 100 / 112) / BurnPerMile));
internal void AddEmptyDeck() => Decks.Add(new Deck(Hull.Columns * Hull.Rows));
private int FacilityCapacity(Facility facility) => Count(facility) * Market.Facilities[(int)facility].Capacity;
public int Count(Facility facility)
{
if (facility == Facility.Extension)
return 0;
int count = 0;
foreach (Deck deck in Decks)
foreach (Facility cell in deck.Cells)
if (cell == facility)
count++;
return count;
}
}
[Serializable]
public sealed class Voyage
{
public int Origin, Destination, Miles, Days, Day, Fare, Guests, RoomDemand, Capacity, FuelBurn, Reserve,
TicketSales, OnboardSales, Crew, Catering, PortFees, FuelExpense, LoanInterest, Principal, ReputationChange;
public int SuiteGuests, SuitePremium;
public string ShipName;
public int ItineraryStartDay, ItineraryLeg, ItineraryLegs;
public OnboardReport Onboard;
public DeparturePlan Plan;
public WeatherCondition Weather;
public int OperatingCash => Crew + Catering + PortFees + (Plan == null ? 0 : Plan.FoodCost + Plan.ProgramCost)
+ (Onboard?.Expenses ?? 0);
public int NetIncome => TicketSales + OnboardSales - OperatingCash - FuelExpense - LoanInterest;
public int CashChange => TicketSales + OnboardSales - OperatingCash - LoanInterest - Principal;
public int RequiredFuel => FuelBurn + Reserve;
}
[Serializable]
public sealed partial class Company
{
public const int SaveVersion = 1;
public const int MaxHistory = 30;
public int Version = SaveVersion;
public int Day = 1, Cash, Debt, Reputation, Voyages;
[NonSerialized] internal int ReservedCash;
public long LifetimeProfit;
public bool Flagship, Bridge;
public int SelectedShip, TutorialStep;
public bool[] Permits = new bool[Market.Ports.Count];
public List<Ship> Fleet = new List<Ship>();
public List<Voyage> History = new List<Voyage>();
public Ship ActiveShip => SelectedShip >= 0 && SelectedShip < Fleet.Count ? Fleet[SelectedShip] : null;
public int AvailableCash => Math.Max(0, Cash - ReservedCash);
public static Company Start(bool financed)
{
var company = new Company
{
Cash = financed ? 580000 : 135000,
Debt = financed ? 500000 : 0,
Reputation = financed ? 12 : 15,
Bridge = financed,
SelectedShip = financed ? -1 : 0
};
company.Permits[0] = company.Permits[1] = true;
if (!financed)
company.Fleet.Add(CreateShip(0, "MV Meridian", true, true));
return company;
}
public bool CanLoad()
{
if (Version != SaveVersion || Day < 1 || Cash < 0 || Debt < 0 || Reputation < 0 || Reputation > 100
|| Voyages < 0 || Permits == null || Permits.Length != Market.Ports.Count || !Permits[0] || !Permits[1]
|| Fleet == null || Fleet.Count > Market.MaxFleet || History == null || History.Count > MaxHistory
|| (Fleet.Count == 0 ? SelectedShip != -1 : SelectedShip < 0 || SelectedShip >= Fleet.Count))
return false;
foreach (Ship ship in Fleet)
{
if (ship == null || string.IsNullOrWhiteSpace(ship.Name) || ship.HullIndex < 0 || ship.HullIndex >= Market.Hulls.Count
|| ship.Port < 0 || ship.Port >= Permits.Length || !Permits[ship.Port] || ship.Condition < 24
|| ship.Condition > 100 || ship.Fare < Market.MinFare || ship.Fare > Market.MaxFare
|| ship.Decks == null || ship.Decks.Count < Market.Hulls[0].StarterDecks || ship.Decks.Count > ship.Hull.MaxDecks
|| ship.Fuel < 0 || double.IsNaN(ship.FuelValue) || double.IsInfinity(ship.FuelValue) || ship.FuelValue < 0)
return false;
foreach (Deck deck in ship.Decks)
{
if (deck?.Cells == null || deck.Cells.Length != ship.Hull.Columns * ship.Hull.Rows
|| !deck.HasValidFootprints(ship.Hull.Columns, ship.HullIndex))
return false;
}
if (ship.Fuel > ship.Tank || !ValidSavedItinerary(ship))
return false;
}
foreach (Voyage voyage in History)
if (voyage == null || voyage.Origin < 0 || voyage.Origin >= Permits.Length
|| voyage.Destination < 0 || voyage.Destination >= Permits.Length)
return false;
return true;
}
public void RestoreHullDecks()
{
foreach (Ship ship in Fleet)
while (ship.Decks.Count < ship.Hull.StarterDecks)
ship.AddEmptyDeck();
}
public string ShipyardBlock(int hullIndex, bool used)
{
HullSpec hull = Market.Hulls[hullIndex];
if (used && hullIndex == Market.Ocean)
return "Ocean Class hulls are available as new commissions.";
if (Fleet.Count >= Market.MaxFleet)
return "The fleet has reached its eight-ship limit.";
if (Voyages < hull.Voyages || Reputation < hull.Reputation)
return $"Requires {hull.Voyages} voyages and {hull.Reputation} reputation.";
if (AvailableCash < (used ? Market.UsedPrice(hullIndex) : hull.Price))
return "The company needs more cash.";
return null;
}
public string Acquire(int hullIndex, bool used, string name)
{
string block = ShipyardBlock(hullIndex, used);
if (block != null)
return block;
if (!used)
{
name = name?.Trim();
if (string.IsNullOrWhiteSpace(name) || name.Length > 24)
return "Enter a ship name of up to 24 characters.";
if (!name.StartsWith("MV ", StringComparison.OrdinalIgnoreCase))
name = "MV " + name;
}
else
name = $"MV Wayfarer {Fleet.Count + 1}";
foreach (Ship ship in Fleet)
if (string.Equals(ship.Name, name, StringComparison.OrdinalIgnoreCase))
return "A vessel already uses that name.";
Cash -= used ? Market.UsedPrice(hullIndex) : Market.Hulls[hullIndex].Price;
Fleet.Add(CreateShip(hullIndex, name, used, false));
SelectedShip = Fleet.Count - 1;
return null;
}
private static Ship CreateShip(int hullIndex, string name, bool used, bool original)
{
var ship = new Ship
{
Name = name,
HullIndex = hullIndex,
Condition = original ? 78 : used ? 72 : 100,
Fare = hullIndex == 0 ? 550 : hullIndex == 1 ? 850 : 1250,
Fuel = original ? 48 : used ? 25 : 0
};
ship.FuelValue = ship.Fuel * Market.FuelPrice(0, 1);
for (int i = 0; i < ship.Hull.StarterDecks; i++)
ship.AddEmptyDeck();
if (used)
{
for (int i = 0; i < 8; i++)
ship.Decks[0].Cells[i] = Facility.Cabin;
ship.Decks[1].Cells[1] = Facility.Dining;
ship.Decks[1].Cells[2] = Facility.Entertainment;
ship.Decks[1].Cells[4] = Facility.Dining;
ship.Decks[1].Cells[5] = Facility.Bar;
ship.Decks[1].Cells[8] = Facility.Amenity;
}
return ship;
}
public int DeckPrice(Ship ship) => 29000 + ship.Decks.Count * 8500 + ship.HullIndex * 13000;
public string AddDeck(Ship ship)
{
int price = DeckPrice(ship);
if (ship.Decks.Count >= ship.Hull.MaxDecks)
return "The hull has reached its deck limit.";
if (AvailableCash < price)
return "The company needs more cash.";
Cash -= price;
ship.AddEmptyDeck();
return null;
}
public string BuildBlock(Ship ship, int deckIndex, int cell, Facility plan)
{
if (ship == null || (uint)deckIndex >= (uint)ship.Decks.Count || (uint)cell >= (uint)ship.Decks[deckIndex].Cells.Length)
return "Select a berth on this ship.";
if ((uint)plan >= (uint)Facility.Extension)
return "Select a facility to build.";
Deck deck = ship.Decks[deckIndex];
int columns = ship.Hull.Columns;
Facility previous = deck.FacilityAt(cell, columns);
if (previous == plan)
return null;
if (plan == Facility.Empty)
return previous == Facility.Tank && ship.Fuel > ship.Tank - Market.Facilities[(int)Facility.Tank].Capacity
? "Burn more fuel before removing this tank." : null;
FacilitySpec spec = Market.Facilities[(int)plan];
if (ship.HullIndex < spec.MinimumHull)
return $"Requires a {Market.Hulls[spec.MinimumHull].Name} hull or larger.";
if (spec.Length > columns - cell % columns)
return $"This facility needs {spec.Length} consecutive berths in one row.";
for (int offset = 0; offset < spec.Length; offset++)
if (deck.Cells[cell + offset] != Facility.Empty)
return spec.Length == 1 ? "Clear this berth before building another facility."
: "Clear every berth in the footprint before fitting this facility.";
if (AvailableCash < spec.Price)
return "The company needs more cash.";
return null;
}
public string Build(Ship ship, int deckIndex, int cell, Facility plan)
{
string block = BuildBlock(ship, deckIndex, cell, plan);
if (block != null)
return block;
Deck deck = ship.Decks[deckIndex];
int anchor = deck.AnchorAt(cell, ship.Hull.Columns);
Facility previous = deck.Cells[anchor];
if (previous == plan)
return null;
FacilitySpec fitted = Market.Facilities[(int)previous];
FacilitySpec selected = Market.Facilities[(int)plan];
Cash += fitted.Price / 4 - selected.Price;
int length = plan == Facility.Empty ? fitted.Length : selected.Length;
deck.Cells[anchor] = plan;
for (int offset = 1; offset < length; offset++)
deck.Cells[anchor + offset] = plan == Facility.Empty ? Facility.Empty : Facility.Extension;
return null;
}
public string PermitBlock(int destination)
{
PortSpec port = Market.Ports[destination];
if (Permits[destination])
return "Permit held.";
if (Reputation < port.Reputation)
return $"Requires {port.Reputation} reputation.";
if (AvailableCash < port.Permit)
return "The company needs more cash.";
return null;
}
public string Permit(int destination)
{
string block = PermitBlock(destination);
if (block != null)
return block;
Cash -= Market.Ports[destination].Permit;
Permits[destination] = true;
return null;
}
public int BunkerCost(Ship ship, int tons) => tons * Market.FuelPrice(ship.Port, Day);
public string Refuel(Ship ship, int tons)
{
if (tons <= 0 || tons > ship.Tank - ship.Fuel)
return "Select a fuel quantity that fits in the tank.";
int cost = BunkerCost(ship, tons);
if (AvailableCash < cost)
return "The company needs more cash.";
Cash -= cost;
ship.Fuel += tons;
ship.FuelValue += cost;
return null;
}
public int ServiceCost(Ship ship) => (100 - ship.Condition) * ship.Hull.HullWearCost;
public string Service(Ship ship)
{
int cost = ServiceCost(ship);
if (AvailableCash < cost)
return "The company needs more cash.";
Cash -= cost;
ship.Condition = 100;
return null;
}
public string PayDownDebt()
{
int payment = Math.Min(25000, Debt);
if (payment <= 0)
return "The company has no outstanding loan.";
if (AvailableCash < payment)
return "The company needs more cash.";
Cash -= payment;
Debt -= payment;
return null;
}
public bool CanDrawBridge => Bridge && AvailableCash < 100000;
public string DrawBridge()
{
if (!CanDrawBridge)
return "Bridge credit is available once when spendable cash falls below $100,000.";
Cash += 125000;
Debt += 125000;
Bridge = false;
return null;
}
public Voyage Forecast(Ship ship, int destination)
{
if (!Market.TryDistance(ship.Port, destination, out int miles))
return null;
PortSpec from = Market.Ports[ship.Port];
PortSpec to = Market.Ports[destination];
int days = 1 + (int)Math.Ceiling(miles / 415.0);
var (fuel, reserve) = LegFuel(ship, miles);
double referenceFare = 330 + days * 88 + to.Appeal * 125;
double fareFactor = Math.Pow(referenceFare / ship.Fare, 1.55);
double season = 1 + .13 * Math.Cos((Day + destination * 13) * 2 * Math.PI / 112);
int recentSailings = 0;
foreach (Voyage voyage in History)
{
if (Day - voyage.Day > 12 || Math.Min(voyage.Origin, voyage.Destination) != Math.Min(ship.Port, destination)
|| Math.Max(voyage.Origin, voyage.Destination) != Math.Max(ship.Port, destination))
continue;
recentSailings++;
}
double saturation = Math.Max(.66, 1 - recentSailings * .085);
double entertainment = Math.Min(1, (double)ship.Entertainment / Math.Max(1, ship.Capacity));
double marketDemand = (150 + ship.Capacity * .50) * from.MarketSize * to.Appeal * season * saturation;
double product = (.66 + Reputation * .006 + entertainment * .20) * (.8 + ship.Condition * .002);
int roomDemand = Math.Max(0, (int)Math.Round(marketDemand * fareFactor * product));
int guests = Math.Min(roomDemand, ship.Capacity);
int suiteBerths = ship.SuiteBerths;
int suiteGuests = suiteBerths == 0 ? 0 : (int)Math.Round(guests * (double)suiteBerths / ship.Beds);
int grandSuiteGuests = suiteGuests == 0 ? 0 : (int)Math.Round(suiteGuests * (double)ship.GrandSuiteBerths / suiteBerths);
int suitePremium = (int)Math.Round(ship.Fare / 100.0 * (
(suiteGuests - grandSuiteGuests) * Market.Facilities[(int)Facility.Suite].FarePremiumPercent
+ grandSuiteGuests * Market.Facilities[(int)Facility.GrandSuite].FarePremiumPercent));
double unitCost = ship.Fuel > 0 ? ship.FuelValue / ship.Fuel : Market.FuelPrice(ship.Port, Day);
return new Voyage
{
Origin = ship.Port,
Destination = destination,
ShipName = ship.Name,
Day = Day + days,
Days = days,
Miles = miles,
Fare = ship.Fare,
Guests = guests,
RoomDemand = roomDemand,
Capacity = ship.Capacity,
FuelBurn = fuel,
Reserve = reserve,
SuiteGuests = suiteGuests,
SuitePremium = suitePremium,
TicketSales = guests * ship.Fare + suitePremium,
OnboardSales = (int)Math.Round(guests * days * (13 + entertainment * 18)),
Crew = ship.Hull.CrewPerDay * days + ship.Decks.Count * 500 * days,
Catering = guests * days * 27,
PortFees = from.Fee / 2 + to.Fee,
FuelExpense = (int)Math.Round(Math.Min(fuel, ship.Fuel) * unitCost
+ Math.Max(0, fuel - ship.Fuel) * Market.FuelPrice(ship.Port, Day)),
LoanInterest = (int)Math.Ceiling(Debt * .13 * days / 365),
Principal = Math.Min(Debt, 850 * days),
ReputationChange = guests == 0 ? -3 : Math.Max(1, (int)Math.Round(2 + 2 * to.Appeal + entertainment * 3))
};
}
public string DepartureBlock(Ship ship, Voyage quote)
{
if (ship == null || quote == null || quote.Origin != ship.Port || !Market.TryDistance(ship.Port, quote.Destination, out _))
return "Select a connected port from your itinerary.";
if (ship.Itinerary is { HasNext: true } itinerary && quote.Destination != itinerary.NextPort)
return $"This itinerary's next stop is {Market.Ports[itinerary.NextPort].Name}.";
if (!Permits[quote.Destination])
return "Obtain a destination permit in Ports.";
if (ship.HullIndex < Market.Ports[quote.Destination].MinimumHull)
return "This destination requires a larger hull class.";
if (ship.Beds == 0 || ship.Meals == 0)
return "Build cabins and dining before carrying guests.";
if (ship.Condition < 25)
return "An overhaul is required before the ship can sail.";
if (quote.RequiredFuel > ship.Tank)
return $"This route needs {quote.RequiredFuel} t. Add a bunker tank or use a larger hull.";
if (ship.Fuel < quote.RequiredFuel)
return $"Buy {quote.RequiredFuel - ship.Fuel} t more fuel to cover the crossing and reserve.";
if (quote.Guests <= 0)
return "Raise demand or lower the fare to attract passengers.";
if (AvailableCash < quote.OperatingCash + quote.LoanInterest + Math.Min(Debt, quote.Principal))
return quote.Plan == null ? "Cash must cover the voyage expenses and loan payment."
: "Cash must cover port orders, voyage expenses and the loan payment.";
return null;
}
public string Sail(Ship ship, int destination, OnboardSession live = null)
{
if (ship == null || !Fleet.Contains(ship))
return "Choose a ship in this fleet.";
Voyage quote = live?.Quote ?? Forecast(ship, destination);
if (live != null && (live.Ship != ship || quote.Origin != ship.Port || quote.Destination != destination || quote.Onboard != null))
return "This sailing has already been settled or belongs to another ship.";
string block = DepartureBlock(ship, quote);
if (block != null)
return block;
if (live != null)
{
live.AdvanceTo(1);
quote.Onboard = live.Report();
quote.OnboardSales = quote.Onboard.Revenue;
quote.FuelBurn = quote.Onboard.FuelBurn;
quote.FuelExpense = (int)Math.Round(quote.FuelBurn * ship.FuelValue / ship.Fuel);
quote.ReputationChange += (int)Math.Round((quote.Onboard.Happiness - 74) / 10.0);
live.SavePrices();
}
quote.Principal = Math.Min(Debt, quote.Principal);
quote.Day = Math.Max(Day, quote.Day);
ship.FuelValue *= (double)(ship.Fuel - quote.FuelBurn) / ship.Fuel;
ship.Fuel -= quote.FuelBurn;
ship.Condition = Market.Clamp(ship.Condition - Math.Max(1, quote.Days / 2) + (quote.Onboard?.Repair ?? 0), 24, 100);
RecordItineraryArrival(ship, quote);
ship.Port = quote.Destination;
Day = quote.Day;
Cash += quote.CashChange;
Debt -= quote.Principal;
Reputation = Market.Clamp(Reputation + quote.ReputationChange, 0, 100);
Voyages++;
LifetimeProfit += quote.NetIncome;
Flagship |= ship.HullIndex == Market.Ocean && ship.Capacity >= 320 && ship.Entertainment >= 160
&& quote.Origin == Market.Bermuda && quote.Destination == Market.Lisbon;
History.Insert(0, quote);
if (History.Count > MaxHistory)
History.RemoveAt(MaxHistory);
return null;
}
}
}