public AirlinerClassMVVM(
            AirlinerClass type,
            int seating,
            int regularSeating,
            int maxseats,
            Boolean changeableSeats = false)
        {
            Type = type.Type;
            Seating = seating;
            RegularSeatingCapacity = regularSeating;
            ChangeableSeats = changeableSeats;
            MaxSeats = maxseats;
            MaxSeatsCapacity = maxseats;
            ChangedFacility = false;

            Facilities = new ObservableCollection<AirlinerFacilityMVVM>();

            foreach (AirlinerFacility.FacilityType facType in Enum.GetValues(typeof(AirlinerFacility.FacilityType)))
            {
                var facility = new AirlinerFacilityMVVM(facType, this);

                foreach (AirlinerFacility fac in AirlinerFacilities.GetFacilities(facType))
                {
                    facility.Facilities.Add(fac);
                }

                AirlinerFacility selectedFacility = type.GetFacility(facType) == null
                    ? AirlinerFacilities.GetBasicFacility(facType)
                    : type.GetFacility(facType);
                facility.SelectedFacility = selectedFacility;

                Facilities.Add(facility);
            }
        }
 public RouteAirlinerClass(AirlinerClass.ClassType type, SeatingType seating, double fareprice)
 {
     Facilities = new List<RouteFacility>();
     FarePrice = fareprice;
     Seating = seating;
     Type = type;
 }
        public static object ShowPopUp(AirlinerClass aClass)
        {
            PopUpWindow window = new PopUpAirlinerClassConfiguration(aClass);
            window.ShowDialog();

            return window.Selected;
        }
        public PopUpAirlinerFacility(AirlinerClass airlinerClass, AirlinerFacility.FacilityType type)
        {
            InitializeComponent();

            this.AirlinerClass = airlinerClass;
            this.Type = type;

            this.Title = "Select " + type.ToString().ToLower();

            this.Width = 400;

            this.Height = 120;

            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            StackPanel mainPanel = new StackPanel();
            mainPanel.Margin = new Thickness(10, 10, 10, 10);

            cbFacility = new ComboBox();
            cbFacility.ItemTemplate = this.Resources["AirlinerFacilityItem"] as DataTemplate;
            cbFacility.SetResourceReference(StyleProperty, "ComboBoxTransparentStyle");

            foreach (AirlinerFacility facility in AirlinerFacilities.GetFacilities(this.Type,GameObject.GetInstance().GameTime.Year))
                cbFacility.Items.Add(facility);

            cbFacility.SelectedItem = this.AirlinerClass.GetFacility(this.Type);

            mainPanel.Children.Add(cbFacility);

            mainPanel.Children.Add(createButtonsPanel());

            this.Content = mainPanel;
               // int serviceLevel, double percentOfSeats, double pricePerSeat
        }
Ejemplo n.º 5
0
        public Airliner(string id, AirlinerType type, string tailNumber, DateTime builtDate)
        {
            ID = id;
            BuiltDate = new DateTime(builtDate.Year, builtDate.Month, builtDate.Day);
            Type = type;
            LastServiceCheck = 0;
            TailNumber = tailNumber;
            Flown = 0;
            Condition = _rnd.Next(90, 100);
            Status = StatusTypes.Normal;

            Classes = new List<AirlinerClass>();

            if (Type.TypeAirliner == AirlinerType.TypeOfAirliner.Passenger)
            {
                var aClass = new AirlinerClass(
                    AirlinerClass.ClassType.EconomyClass,
                    ((AirlinerPassengerType) Type).MaxSeatingCapacity);
                aClass.CreateBasicFacilities(Airline);
                Classes.Add(aClass);
            }

            if (Type.TypeAirliner == AirlinerType.TypeOfAirliner.Cargo)
            {
                var aClass = new AirlinerClass(AirlinerClass.ClassType.EconomyClass, 0);
                aClass.CreateBasicFacilities(Airline);
                Classes.Add(aClass);
            }
        }
 public AirlinerClassConfiguration(AirlinerClass.ClassType type, int seating, int regularseating)
 {
     SeatingCapacity = seating;
     RegularSeatingCapacity = regularseating;
     Type = type;
     Facilities = new List<AirlinerFacility>();
 }
        public static object ShowPopUp(AirlinerClass airlinerClass, AirlinerFacility.FacilityType type)
        {
            PopUpWindow window = new PopUpAirlinerFacility(airlinerClass, type);

            window.ShowDialog();

            return window.Selected == null ? null : window.Selected;
        }
        public PopUpAirlinerClassConfiguration(AirlinerClass aClass)
        {
            InitializeComponent();

            this.AirlinerClass = aClass;

            this.Title = new TextUnderscoreConverter().Convert(aClass.Type.ToString()).ToString();

            this.Width = 400;

            this.Height = 200;

            this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

            StackPanel panelClassFacilities = new StackPanel();

            TextBlock txtHeader = new TextBlock();
            txtHeader.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            txtHeader.SetResourceReference(TextBlock.BackgroundProperty, "HeaderBackgroundBrush");
            txtHeader.FontWeight = FontWeights.Bold;
            txtHeader.Text = string.Format("{0}", new TextUnderscoreConverter().Convert(aClass.Type, null, null, null));

            panelClassFacilities.Children.Add(txtHeader);

            lbFacilities = new ListBox[Enum.GetValues(typeof(AirlinerFacility.FacilityType)).Length];

            int i = 0;
            foreach (AirlinerFacility.FacilityType type in Enum.GetValues(typeof(AirlinerFacility.FacilityType)))
            {
                AirlinerFacility facility = aClass.GetFacility(type);

                lbFacilities[i] = new ListBox();
                lbFacilities[i].ItemContainerStyleSelector = new ListBoxItemStyleSelector();
                lbFacilities[i].ItemTemplate = this.Resources["FleetFacilityItem"] as DataTemplate;

                panelClassFacilities.Children.Add(lbFacilities[i]);

                i++;

            }
            panelClassFacilities.Children.Add(createButtonsPanel());

            this.Content = panelClassFacilities;

            showFacilities();
        }
 public static double GetPassengerPrice(Airport dest1, Airport dest2, AirlinerClass.ClassType type)
 {
     return GetPassengerPrice(dest1, dest2)*GeneralHelpers.ClassToPriceFactor(type);
 }
        //returns the number of passengers for a flight
        public static int GetFlightPassengers(FleetAirliner airliner, AirlinerClass.ClassType type)
        {
            Airport airportCurrent = airliner.CurrentFlight.GetDepartureAirport();
            Airport airportDestination = airliner.CurrentFlight.Entry.Destination.Airport;

            return GetFlightPassengers(airportCurrent, airportDestination, airliner, type);
        }
        public static int GetFlightPassengers(
            Airport airportCurrent,
            Airport airportDestination,
            FleetAirliner airliner,
            AirlinerClass.ClassType type)
        {
            double distance = MathHelpers.GetDistance(airportCurrent, airportDestination);

            Route currentRoute =
                airliner.Routes.Find(
                    r =>
                    r.Stopovers.SelectMany(s => s.Legs)
                     .ToList()
                     .Exists(
                         l =>
                         (l.Destination1 == airportCurrent || l.Destination1 == airportDestination)
                         && (l.Destination2 == airportDestination || l.Destination2 == airportCurrent))
                    || (r.Destination1 == airportCurrent || r.Destination1 == airportDestination)
                    && (r.Destination2 == airportDestination || r.Destination2 == airportCurrent));

            if (currentRoute == null)
            {
                return 0;
            }

            //double basicPrice = GetPassengerPrice(currentRoute.Destination1, currentRoute.Destination2, type);
            //double routePrice = ((PassengerRoute)currentRoute).getFarePrice(type);

            //double priceDiff = basicPrice / routePrice;

            double routeScoreFactor = RouteHelpers.GetRouteTotalScore(currentRoute)/5;

            double demand = airportCurrent.GetDestinationPassengersRate(airportDestination, type);

            double passengerDemand = (demand
                                      + GetFlightConnectionPassengers(
                                          airportCurrent,
                                          airportDestination,
                                          airliner,
                                          type)
                                      + GetNearbyPassengerDemand(airportCurrent, airportDestination, airliner, type))
                                     *GetSeasonFactor(airportDestination)*GetHolidayFactor(airportDestination)
                                     *GetHolidayFactor(airportCurrent);

            passengerDemand *= GameObject.GetInstance().Difficulty.PassengersLevel;
            passengerDemand *= routeScoreFactor;

            if (airliner.Airliner.Airline.MarketFocus == AirlineFocus.Global && distance > 3000
                && airportCurrent.Profile.Country != airportDestination.Profile.Country)
            {
                passengerDemand = passengerDemand*(115/100);
            }

            if (airliner.Airliner.Airline.MarketFocus == AirlineFocus.Regional && distance < 1500)
            {
                passengerDemand = passengerDemand*(115/100);
            }

            if (airliner.Airliner.Airline.MarketFocus == AirlineFocus.Domestic && distance < 1500
                && airportDestination.Profile.Country == airportCurrent.Profile.Country)
            {
                passengerDemand = passengerDemand*(115/100);
            }

            if (airliner.Airliner.Airline.MarketFocus == AirlineFocus.Local && distance < 1000)
            {
                passengerDemand = passengerDemand*(115/100);
            }

            Hub hub = airportDestination.GetHubs().Find(h => h.Airline == airliner.Airliner.Airline);

            if (hub != null)
            {
                switch (hub.Type.Type)
                {
                    case HubType.TypeOfHub.FocusCity:
                        if (airportDestination.Profile.Country == airportCurrent.Profile.Country)
                        {
                            passengerDemand = passengerDemand*1.15;
                        }
                        break;

                    case HubType.TypeOfHub.RegionalHub:
                        if (airportDestination.Profile.Country.Region == airportCurrent.Profile.Country.Region)
                        {
                            passengerDemand = passengerDemand*1.20;
                        }
                        break;

                    case HubType.TypeOfHub.Hub:
                        passengerDemand = passengerDemand*1.20;
                        break;

                    case HubType.TypeOfHub.FortressHub:
                        passengerDemand = passengerDemand*1.30;
                        break;
                }
            }

            var routes = new List<Route>();

            foreach (Airline airline in Airlines.GetAllAirlines())
            {
                var aRoutes = new List<Route>(airline.Routes);

                routes.AddRange(
                    aRoutes.Where(r => r.Type == Route.RouteType.Passenger || r.Type == Route.RouteType.Mixed)
                           .Where(
                               r =>
                               (r.HasAirliner)
                               && (r.Destination1 == airportCurrent || r.Destination1 == airportDestination)
                               && (r.Destination2 == airportDestination || r.Destination2 == airportCurrent)));
                routes.AddRange(
                    aRoutes.Where(r => r.Type == Route.RouteType.Mixed || r.Type == Route.RouteType.Passenger)
                           .Where(
                               r =>
                               r.Stopovers.SelectMany(
                                   s =>
                                   s.Legs.Where(
                                       l =>
                                       r.HasAirliner
                                       && (l.Destination1 == airportCurrent
                                           || l.Destination1 == airportDestination)
                                       && (l.Destination2 == airportDestination
                                           || l.Destination2 == airportCurrent))).Any()));
            }

            double flightsPerDay = Convert.ToDouble(routes.Sum(r => r.TimeTable.Entries.Count))/7;

            passengerDemand = passengerDemand/flightsPerDay;

            double totalCapacity;
            if (routes.Count > 0 && routes.Count(r => r.HasAirliner) > 0)
            {
                totalCapacity =
                    routes.Where(r => r.HasAirliner)
                          .Sum(r => r.GetAirliners().Max(a => a.Airliner.GetTotalSeatCapacity()));
                //SelectMany(r => r.Stopovers.Where(s=>s.Legs.Count >0))).Sum(s=>s.;//a => a.Routes.SelectMany(r=>r.Stopovers.SelectMany(s=>s.Legs.Where(l=>r.HasAirliner && (l.Destination1 == airportCurrent || l.Destination1 == airportDestination) && (l.Destination2 == airportDestination || l.Destination2 == airportCurrent))).Sum(r=>r.getAirliners().Max(a=>a.Airliner.getTotalSeatCapacity()));
            }
            else
            {
                totalCapacity = 0;
                // routes.Where(r => r.HasAirliner).Sum(r => r.getAirliners().Max(a => a.Airliner.getTotalSeatCapacity()));
            }

            double capacityPercent = passengerDemand > totalCapacity ? 1 : passengerDemand/totalCapacity;

            var rations = new Dictionary<Route, double>();

            foreach (Route route in routes)
            {
                double level = ((PassengerRoute) route).GetServiceLevel(type)
                               /((PassengerRoute) route).GetFarePrice(type);

                rations.Add(route, level);
            }

            double totalRatio = rations.Values.Sum();

            double routeRatioPercent = 1;

            if (rations.ContainsKey(currentRoute))
            {
                routeRatioPercent = Math.Max(1, rations[currentRoute]/Math.Max(1, totalRatio));
            }

            IDictionary<Airline, double> airlineScores = new Dictionary<Airline, double>();

            foreach (Airline airline in Airlines.GetAllAirlines())
            {
                airlineScores.Add(airline, airportCurrent.GetAirlineReputation(airline));
            }

            double reputation = StatisticsHelpers.GetRatingScale(airlineScores)[airliner.Airliner.Airline];

            if (reputation < 76)
            {
                reputation = 75;
            }

            double reputationPercent = reputation/100;

            double routePriceDiff = 1; // priceDiff < 0.75 ? priceDiff : 1;

            routePriceDiff *= GameObject.GetInstance().Difficulty.PriceLevel;

            double randomPax = Convert.ToDouble(Rnd.Next(97, 103))/100;

            var pax =
                (int)
                Math.Min(
                    airliner.Airliner.GetAirlinerClass(type).SeatingCapacity,
                    (airliner.Airliner.GetAirlinerClass(type).SeatingCapacity*routeRatioPercent
                     *reputationPercent*capacityPercent*routePriceDiff*randomPax));

            if (pax < 0)
            {
                pax = 0;
            }

            return pax;
        }
        public static void LoadGame(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                WPFMessageBoxResult result = WPFMessageBox.Show(
                    Translator.GetInstance().GetString("MessageBox", "101"),
                    Translator.GetInstance().GetString("MessageBox", "101", "message"),
                    WPFMessageBoxButtons.Ok);
                return;
            }
            string fileName = AppSettings.GetCommonApplicationDataPath() + "\\saves\\" + name + ".sav";

            var doc = new XmlDocument();

            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                Stream s = new GZipStream(fs, CompressionMode.Decompress);
                doc.Load(s);
                s.Close();
            }
            //doc.Load(AppSettings.getDataPath() + "\\saves\\" + name + ".xml");
            XmlElement root = doc.DocumentElement;

            if (root != null)
            {
                DateTime gameTime = DateTime.Parse(root.Attributes["time"].Value, new CultureInfo("de-DE"));
                GameObject.GetInstance().GameTime = gameTime;
            }

            if (root != null)
            {
                XmlNodeList tailnumbersList = root.SelectNodes("//tailnumbers/tailnumber");

                if (tailnumbersList != null)
                    foreach (XmlElement tailnumberNode in tailnumbersList)
                    {
                        Country country = Countries.GetCountry(tailnumberNode.Attributes["country"].Value);

                        if (country != null)
                        {
                            country.TailNumbers.LastTailNumber = tailnumberNode.Attributes["value"].Value;
                        }
                    }
            }

            if (root != null)
            {
                XmlNodeList airlinerTypesList = root.SelectNodes("//airlinertypes/airlinertype");

                if (airlinerTypesList != null)
                    foreach (XmlElement airlinerTypeNode in airlinerTypesList)
                    {
                        var airlinerType =
                            (AirlinerType.TypeOfAirliner)
                            Enum.Parse(typeof (AirlinerType.TypeOfAirliner), airlinerTypeNode.Attributes["type"].Value);
                        AirlinerType baseType = AirlinerTypes.GetType(airlinerTypeNode.Attributes["basetype"].Value);
                        string airlinerTypeName = airlinerTypeNode.Attributes["name"].Value;

                        AirlinerType type = null;

                        if (airlinerType == AirlinerType.TypeOfAirliner.Passenger)
                        {
                            int cabincrew = Convert.ToInt16(airlinerTypeNode.Attributes["cabincrew"].Value);
                            int passengers = Convert.ToInt16(airlinerTypeNode.Attributes["passengers"].Value);
                            int maxclasses = Convert.ToInt16(airlinerTypeNode.Attributes["maxclasses"].Value);

                            type = new AirlinerPassengerType(
                                baseType.Manufacturer,
                                airlinerTypeName,
                                "",
                                passengers,
                                baseType.CockpitCrew,
                                cabincrew,
                                0,
                                0,
                                baseType.Wingspan,
                                baseType.Length,
                                baseType.Weight,
                                0,
                                baseType.Price,
                                maxclasses,
                                0,
                                baseType.FuelCapacity,
                                baseType.Body,
                                baseType.RangeType,
                                baseType.Engine,
                                baseType.Produced,
                                baseType.ProductionRate,
                                false,
                                false);
                        }
                        if (airlinerType == AirlinerType.TypeOfAirliner.Cargo)
                        {
                            double cargo = Convert.ToDouble(
                                airlinerTypeNode.Attributes["cargo"].Value,
                                new CultureInfo("de-DE", false));
                            type = new AirlinerCargoType(
                                baseType.Manufacturer,
                                airlinerTypeName,
                                "",
                                baseType.CockpitCrew,
                                cargo,
                                0,
                                0,
                                baseType.Wingspan,
                                baseType.Length,
                                baseType.Weight,
                                0,
                                baseType.Price,
                                0,
                                baseType.FuelCapacity,
                                baseType.Body,
                                baseType.RangeType,
                                baseType.Engine,
                                baseType.Produced,
                                baseType.ProductionRate,
                                false,
                                false);
                        }
                        if (type != null)
                        {
                            type.BaseType = baseType;

                            AirlinerTypes.AddType(type);
                        }
                    }
            }

            Airliners.Clear();

            if (root != null)
            {
                XmlNodeList airlinersList = root.SelectNodes("//airliners/airliner");

                if (airlinersList != null)
                    Parallel.For(
                        0,
                        airlinersList.Count,
                        i => //foreach (XmlElement airlinerNode in airlinersList)
                            {
                                var airlinerNode = (XmlElement) airlinersList[i];
                                AirlinerType type = AirlinerTypes.GetType(airlinerNode.Attributes["type"].Value);

                                if (type != null)
                                {
                                    string tailnumber = airlinerNode.Attributes["tailnumber"].Value;
                                    string id = airlinerNode.HasAttribute("id") ? airlinerNode.Attributes["id"].Value : tailnumber;

                                    string last_service = airlinerNode.Attributes["last_service"].Value;
                                    DateTime built = DateTime.Parse(
                                        airlinerNode.Attributes["built"].Value,
                                        new CultureInfo("de-DE", false));
                                    double flown = Convert.ToDouble(
                                        airlinerNode.Attributes["flown"].Value,
                                        new CultureInfo("de-DE", false));
                                    double damaged = Convert.ToDouble(
                                        airlinerNode.Attributes["damaged"].Value,
                                        new CultureInfo("de-DE", false));

                                    var airliner = new Airliner(id, type, tailnumber, built) {Condition = damaged, Flown = flown};
                                    airliner.ClearAirlinerClasses();

                                    XmlNodeList airlinerClassList = airlinerNode.SelectNodes("classes/class");

                                    if (airlinerClassList != null)
                                        foreach (XmlElement airlinerClassNode in airlinerClassList)
                                        {
                                            var airlinerClassType =
                                                (AirlinerClass.ClassType)
                                                Enum.Parse(
                                                    typeof (AirlinerClass.ClassType),
                                                    airlinerClassNode.Attributes["type"].Value);
                                            int airlinerClassSeating = Convert.ToInt16(airlinerClassNode.Attributes["seating"].Value);

                                            var aClass = new AirlinerClass(airlinerClassType, airlinerClassSeating);
                                            // chs, 2011-13-10 added for loading of airliner facilities
                                            XmlNodeList airlinerClassFacilitiesList =
                                                airlinerClassNode.SelectNodes("facilities/facility");
                                            if (airlinerClassFacilitiesList != null)
                                                foreach (XmlElement airlinerClassFacilityNode in airlinerClassFacilitiesList)
                                                {
                                                    var airlinerFacilityType =
                                                        (AirlinerFacility.FacilityType)
                                                        Enum.Parse(
                                                            typeof (AirlinerFacility.FacilityType),
                                                            airlinerClassFacilityNode.Attributes["type"].Value);

                                                    AirlinerFacility aFacility = AirlinerFacilities.GetFacility(
                                                        airlinerFacilityType,
                                                        airlinerClassFacilityNode.Attributes["uid"].Value);
                                                    aClass.ForceSetFacility(aFacility);
                                                }

                                            airliner.AddAirlinerClass(aClass);
                                        }

                                    Airliners.AddAirliner(airliner);
                                }
                            });
            }

            Airlines.Clear();

            if (root != null)
            {
                XmlNodeList airlinesList = root.SelectNodes("//airlines/airline[@subsidiary='False']");

                if (airlinesList != null)
                    foreach (XmlElement airlineNode in airlinesList)
                    {
                        LoadAirline(airlineNode);
                    }
            }

            if (root != null)
            {
                XmlNodeList subsidiaryList = root.SelectNodes("//airlines/airline[@subsidiary='True']");

                if (subsidiaryList != null)
                    foreach (XmlElement airlineNode in subsidiaryList)
                    {
                        LoadAirline(airlineNode);
                    }
            }

            if (root != null)
            {
                XmlNodeList airportsList = root.SelectNodes("//airports/airport");

                var airportsToKeep = new List<Airport>();

                if (airportsList != null)
                    foreach (XmlElement airportNode in airportsList)
                    {
                        Airport airport = Airports.GetAirportFromID(airportNode.Attributes["id"].Value);
                        airportsToKeep.Add(airport);

                        /*
                  *   XmlElement airportPaxNode = xmlDoc.CreateElement("paxvalue");
                    airportPaxNode.SetAttribute("from", paxValue.FromYear.ToString());
                    airportPaxNode.SetAttribute("to", paxValue.ToYear.ToString());
                    airportPaxNode.SetAttribute("size", paxValue.Size.ToString());
                    airportPaxNode.SetAttribute("pax", paxValue.Pax.ToString());
                    airportPaxNode.SetAttribute("inflationbefore", paxValue.InflationBeforeYear.ToString());
                    airportPaxNode.SetAttribute("inflationafter", paxValue.InflationAfterYear.ToString());
            */

                        airport.Income = Convert.ToInt64(airportNode.Attributes["income"].Value);

                        airport.Profile.PaxValues.Clear();

                        XmlNodeList paxvaluesList = airportNode.SelectNodes("paxvalues/paxvalue");

                        foreach (XmlElement paxElement in paxvaluesList)
                        {
                            int fromYear = Convert.ToInt16(paxElement.Attributes["from"].Value);
                            int toYear = Convert.ToInt16(paxElement.Attributes["to"].Value);
                            var airportSize =
                                (GeneralHelpers.Size)
                                Enum.Parse(typeof (GeneralHelpers.Size), paxElement.Attributes["size"].Value);
                            double pax = Convert.ToDouble(paxElement.Attributes["pax"].Value);
                            double inflationBefore = Convert.ToDouble(paxElement.Attributes["inflationbefore"].Value);
                            double inflationAfter = Convert.ToDouble(paxElement.Attributes["inflationafter"].Value);

                            var paxValue = new PaxValue(fromYear, toYear, airportSize, pax) {InflationAfterYear = inflationAfter, InflationBeforeYear = inflationBefore};

                            airport.Profile.PaxValues.Add(paxValue);
                        }

                        XmlNodeList runwaysList = airportNode.SelectNodes("runways/runway");

                        foreach (XmlElement runwayElement in runwaysList)
                        {
                            string runwayName = runwayElement.Attributes["name"].Value;
                            long runwayLenght = Convert.ToInt64(runwayElement.Attributes["lenght"].Value);
                            var runwaySurface =
                                (Runway.SurfaceType)
                                Enum.Parse(typeof (Runway.SurfaceType), runwayElement.Attributes["surface"].Value);
                            DateTime runwayDate = DateTime.Parse(
                                runwayElement.Attributes["date"].Value,
                                new CultureInfo("de-DE", false));

                            airport.Runways.Add(new Runway(runwayName, runwayLenght, Runway.RunwayType.Regular, runwaySurface, runwayDate, false));
                        }

                        XmlNodeList airportHubsList = airportNode.SelectNodes("hubs/hub");
                        // airport.Hubs.Clear();

                        foreach (XmlElement airportHubElement in airportHubsList)
                        {
                            Airline airline = Airlines.GetAirline(airportHubElement.Attributes["airline"].Value);
                            // airport.Hubs.Add(new Hub(airline,null));
                        }

                        XmlNodeList airportWeatherList = airportNode.SelectNodes("weathers/weather");

                        for (int i = 0; i < airportWeatherList.Count; i++)
                        {
                            var airportWeatherElement = airportWeatherList[i] as XmlElement;

                            DateTime weatherDate = DateTime.Parse(
                                airportWeatherElement.Attributes["date"].Value,
                                new CultureInfo("de-DE", false));
                            var windDirection =
                                (Weather.WindDirection)
                                Enum.Parse(
                                    typeof (Weather.WindDirection),
                                    airportWeatherElement.Attributes["direction"].Value);
                            var windSpeed =
                                (Weather.eWindSpeed)
                                Enum.Parse(typeof (Weather.eWindSpeed), airportWeatherElement.Attributes["windspeed"].Value);
                            Weather.CloudCover cover = airportWeatherElement.HasAttribute("cover")
                                                           ? (Weather.CloudCover)
                                                             Enum.Parse(typeof (Weather.CloudCover), airportWeatherElement.Attributes["cover"].Value)
                                                           : Weather.CloudCover.Clear;
                            Weather.Precipitation precip = airportWeatherElement.HasAttribute("precip")
                                                               ? (Weather.Precipitation)
                                                                 Enum.Parse(typeof (Weather.Precipitation), airportWeatherElement.Attributes["precip"].Value)
                                                               : Weather.Precipitation.None;
                            double temperatureLow = airportWeatherElement.HasAttribute("temperatureLow")
                                                        ? Convert.ToDouble(
                                                            airportWeatherElement.Attributes["temperaturelow"].Value,
                                                            new CultureInfo("de-DE", false))
                                                        : 0;
                            double temperatureHigh = airportWeatherElement.HasAttribute("temperatureHigh")
                                                         ? Convert.ToDouble(
                                                             airportWeatherElement.Attributes["temperaturehigh"].Value,
                                                             new CultureInfo("de-DE", false))
                                                         : 20;

                            XmlNodeList airportTemperatureList = airportWeatherElement.SelectNodes("temperatures/temperature");
                            var temperatures = new HourlyWeather[airportTemperatureList.Count];

                            int t = 0;
                            foreach (XmlElement airportTemperatureNode in airportTemperatureList)
                            {
                                double hourlyTemperature = Convert.ToDouble(
                                    airportTemperatureNode.Attributes["temp"].Value,
                                    new CultureInfo("de-DE", false));
                                var hourlyCover =
                                    (Weather.CloudCover)
                                    Enum.Parse(typeof (Weather.CloudCover), airportTemperatureNode.Attributes["cover"].Value);
                                var hourlyPrecip =
                                    (Weather.Precipitation)
                                    Enum.Parse(
                                        typeof (Weather.Precipitation),
                                        airportTemperatureNode.Attributes["precip"].Value);
                                var hourlyWindspeed =
                                    (Weather.eWindSpeed)
                                    Enum.Parse(
                                        typeof (Weather.eWindSpeed),
                                        airportTemperatureNode.Attributes["windspeed"].Value);
                                var hourlyDirection =
                                    (Weather.WindDirection)
                                    Enum.Parse(
                                        typeof (Weather.WindDirection),
                                        airportTemperatureNode.Attributes["direction"].Value);

                                temperatures[t] = new HourlyWeather(
                                    hourlyTemperature,
                                    hourlyCover,
                                    hourlyPrecip,
                                    hourlyWindspeed,
                                    hourlyDirection);
                                t++;
                            }

                            airport.Weather[i] = new Weather(
                                weatherDate,
                                windSpeed,
                                windDirection,
                                cover,
                                precip,
                                temperatures,
                                temperatureLow,
                                temperatureHigh);
                        }

                        XmlNodeList airportStatList = airportNode.SelectNodes("stats/stat");

                        foreach (XmlElement airportStatNode in airportStatList)
                        {
                            int year = Convert.ToInt32(airportStatNode.Attributes["year"].Value);
                            Airline airline = Airlines.GetAirline(airportStatNode.Attributes["airline"].Value);
                            string statType = airportStatNode.Attributes["type"].Value;
                            int statValue = Convert.ToInt32(airportStatNode.Attributes["value"].Value);
                            airport.Statistics.SetStatisticsValue(
                                year,
                                airline,
                                StatisticsTypes.GetStatisticsType(statType),
                                statValue);
                        }

                        XmlNodeList airportFacilitiesList = airportNode.SelectNodes("facilities/facility");
                        airport.ClearFacilities();

                        foreach (XmlElement airportFacilityNode in airportFacilitiesList)
                        {
                            Airline airline = Airlines.GetAirline(airportFacilityNode.Attributes["airline"].Value);
                            AirportFacility airportFacility =
                                AirportFacilities.GetFacility(airportFacilityNode.Attributes["name"].Value);
                            DateTime finishedDate = DateTime.Parse(
                                airportFacilityNode.Attributes["finished"].Value,
                                new CultureInfo("de-DE", false));

                            airport.AddAirportFacility(airline, airportFacility, finishedDate);
                        }
                        airport.Terminals.Clear();

                        XmlNodeList terminalsList = airportNode.SelectNodes("terminals/terminal");

                        foreach (XmlElement terminalNode in terminalsList)
                        {
                            DateTime deliveryDate = DateTime.Parse(
                                terminalNode.Attributes["delivery"].Value,
                                new CultureInfo("de-DE", false));
                            Airline owner = Airlines.GetAirline(terminalNode.Attributes["owner"].Value);
                            string terminalName = terminalNode.Attributes["name"].Value;
                            int gates = Convert.ToInt32(terminalNode.Attributes["totalgates"].Value);

                            var terminal = new Terminal(airport, owner, terminalName, gates, deliveryDate, Terminal.TerminalType.Passenger);
                            terminal.Gates.Clear();

                            XmlNodeList airportGatesList = terminalNode.SelectNodes("gates/gate");

                            foreach (XmlElement airportGateNode in airportGatesList)
                            {
                                DateTime gateDeliveryDate = DateTime.Parse(
                                    airportGateNode.Attributes["delivery"].Value,
                                    new CultureInfo("de-DE", false));
                                var gate = new Gate(gateDeliveryDate);

                                terminal.Gates.AddGate(gate);
                            }

                            airport.AddTerminal(terminal);
                        }
                        airport.ClearAirlineContracts();

                        XmlNodeList contractsList = airportNode.SelectNodes("contracts/contract");

                        foreach (XmlElement contractNode in contractsList)
                        {
                            Airline contractAirline = Airlines.GetAirline(contractNode.Attributes["airline"].Value);
                            int contractLength = Convert.ToInt16(contractNode.Attributes["length"].Value);
                            DateTime contractDate = DateTime.Parse(
                                contractNode.Attributes["date"].Value,
                                new CultureInfo("de-DE", false));
                            int contractGates = Convert.ToInt16(contractNode.Attributes["gates"].Value);
                            double contractPayment = Convert.ToDouble(
                                contractNode.Attributes["payment"].Value,
                                new CultureInfo("de-DE", false));
                            Boolean contractExclusive = Convert.ToBoolean(contractNode.Attributes["exclusive"].Value);
                            Terminal contractTerminal = contractNode.HasAttribute("terminal")
                                                            ? airport.Terminals.AirportTerminals.Find(
                                                                t => t.Name == contractNode.Attributes["terminal"].Value)
                                                            : null;

                            var contract = new AirportContract(
                                contractAirline,
                                airport,
                                AirportContract.ContractType.Full,
                                Terminal.TerminalType.Passenger,
                                contractDate,
                                contractGates,
                                contractLength,
                                contractPayment,
                                true,
                                false,
                                contractExclusive,
                                contractTerminal);
                            AirportHelpers.AddAirlineContract(contract);
                        }
                    }

                Airports.RemoveAirports(a => !airportsToKeep.Contains(a));
            }

            XmlNodeList airportDestinationsList = root.SelectNodes("//airportdestinations/airportdestination");

            foreach (XmlElement airportDestinationElement in airportDestinationsList)
            {
                Airport targetAirport = Airports.GetAirport(airportDestinationElement.Attributes["id"].Value);

                if (targetAirport != null)
                {
                    targetAirport.ClearDestinationPassengers();

                    XmlNodeList destinationsList = airportDestinationElement.SelectNodes("destinations/destination");

                    Parallel.For(
                        0,
                        destinationsList.Count,
                        i => //foreach (XmlElement destinationElement in destinationsList)
                            {
                                var destinationElement = (XmlElement) destinationsList[i];
                                Airport destAirport = Airports.GetAirport(destinationElement.Attributes["id"].Value);

                                if (destAirport != null)
                                {
                                    ushort rate = ushort.Parse(destinationElement.Attributes["rate"].Value);
                                    long destPassengers = Convert.ToInt64(destinationElement.Attributes["passengers"].Value);

                                    targetAirport.AddPassengerDestinationStatistics(destAirport, destPassengers);
                                    targetAirport.AddDestinationPassengersRate(
                                        new DestinationDemand(destAirport.Profile.IATACode, rate));

                                    if (destinationElement.HasAttribute("cargo"))
                                    {
                                        targetAirport.AddDestinationCargoRate(
                                            new DestinationDemand(
                                                destAirport.Profile.IATACode,
                                                ushort.Parse(destinationElement.Attributes["cargo"].Value)));
                                        targetAirport.AddCargoDestinationStatistics(
                                            destAirport,
                                            Convert.ToDouble(
                                                destinationElement.Attributes["cargostats"].Value,
                                                new CultureInfo("de-DE", false)));
                                    }
                                }
                            });
                }
            }
            Instructors.Clear();

            XmlNodeList instructorsList = root.SelectNodes("//instructors/instructor");

            foreach (XmlElement instructorNode in instructorsList)
            {
                string firstname = instructorNode.Attributes["firstname"].Value;
                string lastname = instructorNode.Attributes["lastname"].Value;
                DateTime birthdate = DateTime.Parse(
                    instructorNode.Attributes["birthdate"].Value,
                    new CultureInfo("de-DE", false));
                Town town = Towns.GetTown(instructorNode.Attributes["town"].Value);
                //Pilot.PilotRating rating = (Pilot.PilotRating)Enum.Parse(typeof(Pilot.PilotRating), instructorNode.Attributes["rating"].Value);
                string id = instructorNode.Attributes["id"].Value;

                var instructor = new Instructor(
                    new PilotProfile(firstname, lastname, birthdate, town),
                    PilotRatings.GetRating("A"));

                if (id != "-")
                {
                    FlightSchool fs =
                        Airlines.GetAllAirlines()
                                .SelectMany(a => a.FlightSchools).FirstOrDefault(f => f.ID == id);
                    instructor.FlightSchool = fs;
                    fs.AddInstructor(instructor);
                }

                XmlNodeList studentsList = instructorNode.SelectNodes("students/student");

                foreach (XmlElement studentNode in studentsList)
                {
                    PilotStudent student =
                        instructor.FlightSchool.Students.Find(
                            s => s.Profile.Name == studentNode.Attributes["name"].Value);
                    student.Instructor = instructor;
                    instructor.AddStudent(student);
                }

                Instructors.AddInstructor(instructor);
            }

            if (Instructors.GetInstructors().Count == 0)
            {
                GeneralHelpers.CreateInstructors(75*Airlines.GetAllAirlines().Count);
            }

            Pilots.Clear();

            XmlNodeList pilotsList = root.SelectNodes("//pilots/pilot");

            foreach (XmlElement pilotNode in pilotsList)
            {
                string firstname = pilotNode.Attributes["firstname"].Value;
                string lastname = pilotNode.Attributes["lastname"].Value;
                DateTime birthdate = DateTime.Parse(
                    pilotNode.Attributes["birthdate"].Value,
                    new CultureInfo("de-DE", false));
                Town town = Towns.GetTown(pilotNode.Attributes["town"].Value);
                DateTime educationdate = DateTime.Parse(
                    pilotNode.Attributes["education"].Value,
                    new CultureInfo("de-DE", false));

                //Pilot.PilotRating rating = (Pilot.PilotRating)Enum.Parse(typeof(Pilot.PilotRating), pilotNode.Attributes["rating"].Value);

                var pilot = new Pilot(
                    new PilotProfile(firstname, lastname, birthdate, town),
                    educationdate,
                    PilotRatings.GetRating("B"));

                if (pilotNode.Attributes["airline"].Value != "-")
                {
                    Airline pilotAirline = Airlines.GetAirline(pilotNode.Attributes["airline"].Value);
                    DateTime airlinesigneddate = DateTime.Parse(
                        pilotNode.Attributes["airlinesigned"].Value,
                        new CultureInfo("de-DE", false));

                    pilotAirline.AddPilot(pilot);
                    pilot.AirlineSignedDate = airlinesigneddate;

                    if (pilotNode.Attributes["airliner"].Value != "-")
                    {
                        FleetAirliner airliner =
                            pilotAirline.Fleet.Find(f => f.Airliner.ID == pilotNode.Attributes["airliner"].Value);

                        if (airliner != null)
                        {
                            pilot.Airliner = airliner;
                            airliner.AddPilot(pilot);
                        }
                    }
                }

                Pilots.AddPilot(pilot);
            }

            if (Pilots.GetNumberOfPilots() == 0)
            {
                var rnd = new Random();

                GeneralHelpers.CreatePilots(100*Airlines.GetAllAirlines().Count);

                foreach (FleetAirliner airliner in Airlines.GetAllAirlines().SelectMany(a => a.Fleet))
                {
                    Pilot pilot = Pilots.GetPilots()[rnd.Next(Pilots.GetNumberOfPilots())];
                    airliner.Airliner.Airline.AddPilot(pilot);
                    pilot.Airliner = airliner;
                    airliner.AddPilot(pilot);
                }
            }

            Alliances.Clear();

            XmlNodeList alliancesList = root.SelectNodes("//alliances/alliance");

            foreach (XmlElement allianceNode in alliancesList)
            {
                string allianceName = allianceNode.Attributes["name"].Value;
                DateTime formationDate = DateTime.Parse(
                    allianceNode.Attributes["formation"].Value,
                    new CultureInfo("de-DE"));
                Airport allianceHeadquarter = Airports.GetAirport(allianceNode.Attributes["headquarter"].Value);

                var alliance = new Alliance(formationDate, allianceName, allianceHeadquarter);

                XmlNodeList membersList = allianceNode.SelectNodes("members/member");

                foreach (XmlElement memberNode in membersList)
                {
                    Airline allianceMember = Airlines.GetAirline(memberNode.Attributes["airline"].Value);
                    DateTime joinedDate = DateTime.Parse(
                        memberNode.Attributes["joined"].Value,
                        new CultureInfo("de-DE"));

                    if (allianceMember != null)
                    {
                        alliance.AddMember(new AllianceMember(allianceMember, joinedDate));
                    }
                }

                XmlNodeList pendingsList = allianceNode.SelectNodes("pendings/pending");

                foreach (XmlElement pendingNode in pendingsList)
                {
                    Airline pendingAirline = Airlines.GetAirline(pendingNode.Attributes["airline"].Value);
                    DateTime pendingDate = DateTime.Parse(
                        pendingNode.Attributes["date"].Value,
                        new CultureInfo("de-DE"));
                    var pendingType =
                        (PendingAllianceMember.AcceptType)
                        Enum.Parse(typeof (PendingAllianceMember.AcceptType), pendingNode.Attributes["type"].Value);

                    alliance.AddPendingMember(
                        new PendingAllianceMember(pendingDate, alliance, pendingAirline, pendingType));
                }

                Alliances.AddAlliance(alliance);
            }
            Configurations.Clear();

            XmlNodeList configurationsList = root.SelectNodes("//configurations/configuration");

            foreach (XmlElement confElement in configurationsList)
            {
                string confName = confElement.Attributes["name"].Value;
                string confid = confElement.Attributes["id"].Value;
                Boolean standard = Convert.ToBoolean(confElement.Attributes["standard"].Value);

                int minimumSeats = Convert.ToInt16(confElement.Attributes["minimumseats"].Value);

                var configuration = new AirlinerConfiguration(confName, minimumSeats, standard) {ID = confid};

                XmlNodeList classesList = confElement.SelectNodes("classes/class");

                foreach (XmlElement classElement in classesList)
                {
                    int seating = Convert.ToInt16(classElement.Attributes["seating"].Value);
                    int regularseating = Convert.ToInt16(classElement.Attributes["regularseating"].Value);
                    var classType =
                        (AirlinerClass.ClassType)
                        Enum.Parse(typeof (AirlinerClass.ClassType), classElement.Attributes["type"].Value);

                    var classConf = new AirlinerClassConfiguration(classType, seating, regularseating);
                    foreach (
                        AirlinerFacility.FacilityType facType in Enum.GetValues(typeof (AirlinerFacility.FacilityType)))
                    {
                        string facUid = classElement.Attributes[facType.ToString()].Value;

                        classConf.AddFacility(AirlinerFacilities.GetFacility(facType, facUid));
                    }

                    configuration.AddClassConfiguration(classConf);
                }
                Configurations.AddConfiguration(configuration);
            }

            XmlNodeList routeConfigurationsList =
                root.SelectNodes("//routeclassesconfigurations/routeclassesconfiguration");

            foreach (XmlElement confElement in routeConfigurationsList)
            {
                string routeConfName = confElement.Attributes["name"].Value;
                string confid = confElement.Attributes["id"].Value;
                Boolean standard = Convert.ToBoolean(confElement.Attributes["standard"].Value);

                XmlNodeList classesList = confElement.SelectNodes("classes/class");

                var classesConfiguration = new RouteClassesConfiguration(routeConfName, standard) {ID = confid};

                foreach (XmlElement classElement in classesList)
                {
                    var classType =
                        (AirlinerClass.ClassType)
                        Enum.Parse(typeof (AirlinerClass.ClassType), classElement.Attributes["type"].Value);

                    var classConf = new RouteClassConfiguration(classType);
                    foreach (RouteFacility.FacilityType facType in Enum.GetValues(typeof (RouteFacility.FacilityType)))
                    {
                        if (classElement.HasAttribute(facType.ToString()))
                        {
                            string facilityName = classElement.Attributes[facType.ToString()].Value;

                            classConf.AddFacility(
                                RouteFacilities.GetFacilities(facType).Find(f => f.Name == facilityName));
                        }
                    }

                    classesConfiguration.AddClass(classConf);
                }

                Configurations.AddConfiguration(classesConfiguration);
            }

            var difficultyNode = (XmlElement) root.SelectSingleNode("//difficulty");
            string difficultyName = difficultyNode.Attributes["name"].Value;
            double moneyLevel = Convert.ToDouble(
                difficultyNode.Attributes["money"].Value,
                new CultureInfo("de-DE", false));
            double priceLevel = Convert.ToDouble(
                difficultyNode.Attributes["price"].Value,
                new CultureInfo("de-DE", false));
            double loanLevel = Convert.ToDouble(
                difficultyNode.Attributes["loan"].Value,
                new CultureInfo("de-DE", false));
            double passengersLevel = Convert.ToDouble(
                difficultyNode.Attributes["passengers"].Value,
                new CultureInfo("de-DE", false));
            double aiLevel = Convert.ToDouble(difficultyNode.Attributes["ai"].Value, new CultureInfo("de-DE", false));

            GameObject.GetInstance().Difficulty = new DifficultyLevel(
                difficultyName,
                moneyLevel,
                loanLevel,
                passengersLevel,
                priceLevel,
                aiLevel,
                1);

            var scenarioNode = (XmlElement) root.SelectSingleNode("//scenario");

            if (scenarioNode != null)
            {
                Scenario scenario = Scenarios.GetScenario(scenarioNode.Attributes["name"].Value);

                var so = new ScenarioObject(scenario) {IsSuccess = Convert.ToBoolean(scenarioNode.Attributes["success"].Value)};

                if (scenarioNode.HasAttribute("failed"))
                {
                    so.ScenarioFailed = scenario.Failures.Find(f => f.ID == scenarioNode.Attributes["failed"].Value);
                }

                XmlNodeList failuresList = scenarioNode.SelectNodes("failures/failure");

                foreach (XmlElement failureNode in failuresList)
                {
                    ScenarioFailure failure = scenario.Failures.Find(f => f.ID == failureNode.Attributes["id"].Value);
                    int failureCount = Convert.ToInt16(failureNode.Attributes["count"].Value);
                    DateTime lastFailureTime = DateTime.Parse(
                        failureNode.Attributes["lastfailuretime"].Value,
                        new CultureInfo("de-DE", false));

                    so.GetScenarioFailure(failure).LastFailureTime = lastFailureTime;
                    so.GetScenarioFailure(failure).Failures = failureCount;
                }

                GameObject.GetInstance().Scenario = so;
            }

            var gameSettingsNode = (XmlElement) root.SelectSingleNode("//gamesettings");

            GameObject.GetInstance().Name = gameSettingsNode.Attributes["name"].Value;

            Airline humanAirline = Airlines.GetAirline(gameSettingsNode.Attributes["human"].Value);
            GameObject.GetInstance().SetHumanAirline(humanAirline);

            Airline mainAirline = Airlines.GetAirline(gameSettingsNode.Attributes["mainairline"].Value);
            GameObject.GetInstance().MainAirline = mainAirline;

            double fuelPrice = Convert.ToDouble(
                gameSettingsNode.Attributes["fuelprice"].Value,
                new CultureInfo("de-DE", false));

            GameTimeZone timezone =
                TimeZones.GetTimeZones()
                         .Find(
                             gtz => gtz.UTCOffset == TimeSpan.Parse(gameSettingsNode.Attributes["timezone"].Value));
            GameObject.GetInstance().TimeZone = timezone;

            Infrastructure.Settings.GetInstance().MailsOnLandings =
                Convert.ToBoolean(gameSettingsNode.Attributes["mailonlandings"].Value);
            Infrastructure.Settings.GetInstance().MailsOnBadWeather =
                Convert.ToBoolean(gameSettingsNode.Attributes["mailonbadweather"].Value);

            Infrastructure.Settings.GetInstance().AirportCodeDisplay =
                (AirportCode)
                Enum.Parse(typeof (AirportCode), gameSettingsNode.Attributes["airportcode"].Value);
            if (gameSettingsNode.HasAttribute("minutesperturn"))
            {
                Infrastructure.Settings.GetInstance().MinutesPerTurn =
                    Convert.ToInt16(gameSettingsNode.Attributes["minutesperturn"].Value);
            }
            AppSettings.GetInstance().SetLanguage(Languages.GetLanguage(gameSettingsNode.Attributes["language"].Value));
            GameObject.GetInstance().DayRoundEnabled = Convert.ToBoolean(gameSettingsNode.Attributes["dayround"].Value);

            XmlNodeList itemsList = gameSettingsNode.SelectNodes("calendaritems/calendaritem");

            CalendarItems.Clear();

            foreach (XmlElement itemNode in itemsList)
            {
                var itemType =
                    (CalendarItem.ItemType) Enum.Parse(typeof (CalendarItem.ItemType), itemNode.Attributes["type"].Value);
                DateTime itemDate = DateTime.Parse(itemNode.Attributes["date"].Value, new CultureInfo("de-DE", false));
                string itemHeader = itemNode.Attributes["header"].Value;
                string itemSubject = itemNode.Attributes["subject"].Value;

                CalendarItems.AddCalendarItem(new CalendarItem(itemType, itemDate, itemHeader, itemSubject));
            }

            XmlNodeList newsList = gameSettingsNode.SelectNodes("news/new");
            GameObject.GetInstance().NewsBox.Clear();

            foreach (XmlElement newsNode in newsList)
            {
                DateTime newsDate = DateTime.Parse(newsNode.Attributes["date"].Value, new CultureInfo("de-DE", false));
                var newsType = (News.NewsType) Enum.Parse(typeof (News.NewsType), newsNode.Attributes["type"].Value);
                string newsSubject = newsNode.Attributes["subject"].Value;
                string newsBody = newsNode.Attributes["body"].Value;
                Boolean newsIsRead = Convert.ToBoolean(newsNode.Attributes["isread"].Value);

                var news = new News(newsType, newsDate, newsSubject, newsBody) {IsRead = newsIsRead};

                GameObject.GetInstance().NewsBox.AddNews(news);
            }
            /*
               foreach (Airline airline in Airlines.GetAllAirlines())
               {
                   foreach (Route route in airline.Routes)
                   {
                       Gate gate1 = route.Destination1.Terminals.getEmptyGate(airline);
                       Gate gate2 = route.Destination2.Terminals.getEmptyGate(airline);

                       if (gate1!=null) gate1.Route = route;
                       if (gate2!=null) gate2.Route = route;

                   }
               }

               */
        }
Ejemplo n.º 13
0
 //returns the total number of passengers
 //returns the flight airliner class for a specific class type
 public FlightAirlinerClass GetFlightAirlinerClass(AirlinerClass.ClassType type)
 {
     return Classes.Find(c => c.AirlinerClass.Type == type);
 }
        private static double GetFlightConnectionPassengers(
            Airport airportCurrent,
            Airport airportDestination,
            FleetAirliner airliner,
            AirlinerClass.ClassType type)
        {
            double legDistance = MathHelpers.GetDistance(airportCurrent, airportDestination);

            List<Route> routesFromDestination =
                airliner.Airliner.Airline.Routes.FindAll(
                    r =>
                    !r.IsCargoRoute
                    && ((r.Destination2 == airportDestination || r.Destination1 == airportDestination)
                        && (r.Destination1 != airportCurrent && r.Destination2 != airportCurrent)));
            List<Route> routesToOrigin =
                airliner.Airliner.Airline.Routes.FindAll(
                    r =>
                    !r.IsCargoRoute
                    && ((r.Destination1 == airportCurrent || r.Destination2 == airportCurrent)
                        && (r.Destination2 != airportDestination && r.Destination1 != airportDestination)));

            double demandDestination = (from PassengerRoute route in routesFromDestination
                                        let tDest = route.Destination1 == airportDestination ? route.Destination2 : route.Destination1
                                        let totalDistance = airportCurrent.Profile.Coordinates.ConvertToGeoCoordinate().GetDistanceTo(tDest.Profile.Coordinates.ConvertToGeoCoordinate())/1000
                                        let directRoutes = AirportHelpers.GetNumberOfAirportsRoutes(airportCurrent, tDest)
                                        where route.GetDistance() + legDistance < totalDistance*3 && directRoutes < 2
                                        select airportCurrent.GetDestinationPassengersRate(tDest, type)
                                        into demand select (demand*0.25)).Sum();

            double demandOrigin = (from PassengerRoute route in routesToOrigin
                                   let tDest = route.Destination1 == airportCurrent ? route.Destination2 : route.Destination1
                                   let totalDistance = tDest.Profile.Coordinates.ConvertToGeoCoordinate().GetDistanceTo(airportDestination.Profile.Coordinates.ConvertToGeoCoordinate())/1000
                                   let directRoutes = AirportHelpers.GetNumberOfAirportsRoutes(tDest, airportDestination)
                                   where route.GetDistance() + legDistance < totalDistance*3 && directRoutes < 2
                                   select tDest.GetDestinationPassengersRate(airportDestination, type)
                                   into demand select (demand*0.25)).Sum();
            //alliances & codesharings
            if (airliner.Airliner.Airline.Alliances.Count > 0 || airliner.Airliner.Airline.Codeshares.Count > 0)
            {
                IEnumerable<Route> allianceRoutesFromDestination =
                    airliner.Airliner.Airline.Alliances.SelectMany(
                        a =>
                        a.Members.Where(m => m.Airline != airliner.Airliner.Airline)
                         .SelectMany(
                             m =>
                             m.Airline.Routes.FindAll(
                                 r =>
                                 ((r.Destination2 == airportDestination
                                   || r.Destination1 == airportDestination)
                                  && (r.Destination1 != airportCurrent
                                      && r.Destination2 != airportCurrent)))));
                IEnumerable<Route> allianceRoutesToOrigin =
                    airliner.Airliner.Airline.Alliances.SelectMany(
                        a =>
                        a.Members.Where(m => m.Airline != airliner.Airliner.Airline)
                         .SelectMany(
                             m =>
                             m.Airline.Routes.FindAll(
                                 r =>
                                 ((r.Destination1 == airportCurrent || r.Destination2 == airportCurrent)
                                  && (r.Destination2 != airportDestination
                                      && r.Destination1 != airportDestination)))));

                IEnumerable<CodeshareAgreement> codeshares =
                    airliner.Airliner.Airline.Codeshares.Where(
                        a =>
                        (a.Airline2 == airliner.Airliner.Airline
                         && a.Type == CodeshareAgreement.CodeshareType.OneWay)
                        || a.Type == CodeshareAgreement.CodeshareType.BothWays);

                var codeshareAgreements = codeshares as CodeshareAgreement[] ?? codeshares.ToArray();
                IEnumerable<Route> codesharingRoutesFromDestination =
                    codeshareAgreements.Select(a => a.Airline1 == airliner.Airliner.Airline ? a.Airline2 : a.Airline1)
                              .SelectMany(
                                  a =>
                                  a.Routes.FindAll(
                                      r =>
                                      ((r.Destination2 == airportDestination || r.Destination1 == airportDestination)
                                       && (r.Destination1 != airportCurrent && r.Destination2 != airportCurrent))));
                IEnumerable<Route> codesharingRoutesToOrigin =
                    codeshareAgreements.Select(a => a.Airline1 == airliner.Airliner.Airline ? a.Airline2 : a.Airline1)
                              .SelectMany(
                                  a =>
                                  a.Routes.FindAll(
                                      r =>
                                      ((r.Destination1 == airportCurrent || r.Destination2 == airportCurrent)
                                       && (r.Destination2 != airportDestination
                                           && r.Destination1 != airportDestination))));

                allianceRoutesFromDestination = allianceRoutesFromDestination.Union(codesharingRoutesFromDestination);
                allianceRoutesToOrigin = allianceRoutesToOrigin.Union(codesharingRoutesToOrigin);

                foreach (PassengerRoute route in allianceRoutesFromDestination.Where(r => !r.IsCargoRoute))
                {
                    Airport tDest = route.Destination1 == airportDestination ? route.Destination2 : route.Destination1;

                    double totalDistance =
                        airportCurrent.Profile.Coordinates.ConvertToGeoCoordinate()
                                      .GetDistanceTo(tDest.Profile.Coordinates.ConvertToGeoCoordinate())/1000;

                    int directRoutes = AirportHelpers.GetNumberOfAirportsRoutes(airportCurrent, tDest);

                    if (route.GetDistance() + legDistance < totalDistance*3 && directRoutes < 2)
                    {
                        double demand = airportCurrent.GetDestinationPassengersRate(tDest, type);
                        demandDestination += demand;
                    }
                }

                foreach (PassengerRoute route in allianceRoutesToOrigin.Where(r => !r.IsCargoRoute))
                {
                    Airport tDest = route.Destination1 == airportCurrent ? route.Destination2 : route.Destination1;

                    double totalDistance =
                        tDest.Profile.Coordinates.ConvertToGeoCoordinate()
                             .GetDistanceTo(airportDestination.Profile.Coordinates.ConvertToGeoCoordinate())/1000;

                    int directRoutes = AirportHelpers.GetNumberOfAirportsRoutes(tDest, airportDestination);

                    if (route.GetDistance() + legDistance < totalDistance*3 && directRoutes < 2)
                    {
                        double demand = tDest.GetDestinationPassengersRate(airportDestination, type);
                        demandOrigin += demand;
                    }
                }
            }

            return demandOrigin + demandDestination;
        }
 public AirlinerClassItem(AirlinerClass aClass, Boolean canDelete)
 {
     this.AirlinerClass = aClass;
     this.CanDelete = canDelete;
 }
Ejemplo n.º 16
0
 private int GetSeatingCapacity(AirlinerClass.ClassType classType)
 {
     return Classes.Exists(x => x.Type == classType) ? Classes.Find(x => x.Type == classType).SeatingCapacity : 0;
 }
Ejemplo n.º 17
0
        public ushort GetDestinationPassengersRate(Airport destination, AirlinerClass.ClassType type)
        {
            DestinationDemand pax = DestinationPassengers.Find(a => a.Destination == destination.Profile.IATACode);

            Array values = Enum.GetValues(typeof (AirlinerClass.ClassType));

            int classFactor = 0;

            int i = 1;

            foreach (AirlinerClass.ClassType value in values)
            {
                if (value == type)
                {
                    classFactor = i;
                }
                i++;
            }

            if (pax == null)
            {
                return Statics.GetDestinationPassengersRate(destination, type);
            }
            return
                (ushort)
                (Statics.GetDestinationPassengersRate(destination, type) + (ushort) (pax.Rate/classFactor));
        }
Ejemplo n.º 18
0
 public void RemoveAirlinerClass(AirlinerClass airlinerClass)
 {
     Classes.Remove(airlinerClass);
 }
Ejemplo n.º 19
0
 //returns the total amount of seat capacity
 //returns the airliner class for the airliner
 public AirlinerClass GetAirlinerClass(AirlinerClass.ClassType type)
 {
     if (Classes.Exists(c => c.Type == type))
     {
         return Classes.Find(c => c.Type == type);
     }
     return Classes[0];
 }
Ejemplo n.º 20
0
 //adds a new airliner class to the airliner
 public void AddAirlinerClass(AirlinerClass airlinerClass)
 {
     if (airlinerClass != null)
     {
         if (Classes.Exists(c => c.Type == airlinerClass.Type))
         {
             Classes[Classes.FindIndex(c => c.Type == airlinerClass.Type)] = airlinerClass;
         }
         else
         {
             Classes.Add(airlinerClass);
             if (airlinerClass.GetFacilities().Count == 0)
             {
                 airlinerClass.CreateBasicFacilities(Airline);
             }
         }
     }
 }
        public static int GetStopoverFlightPassengers(
            FleetAirliner airliner,
            AirlinerClass.ClassType type,
            Airport dept,
            Airport dest,
            List<Route> routes,
            bool isInbound)
        {
            Route currentRoute =
                routes.Find(
                    r =>
                    (r.Destination1 == dept && r.Destination2 == dest)
                    || (r.Destination2 == dept && r.Destination1 == dest));
            int index = routes.IndexOf(currentRoute);

            int passengers = 0;
            for (int i = 0; i <= index; i++)
            {
                if (isInbound)
                {
                    passengers += GetFlightPassengers(routes[i].Destination2, dest, airliner, type);
                }
                else
                {
                    passengers += GetFlightPassengers(routes[i].Destination1, dest, airliner, type);
                }
            }

            if (passengers < 0)
            {
                passengers = 0;
            }

            return Math.Min(airliner.Airliner.GetAirlinerClass(type).SeatingCapacity, passengers);
        }
 public RouteClassConfiguration(AirlinerClass.ClassType type)
 {
     Type = type;
     Facilities = new List<RouteFacility>();
 }
        //returns the number of passengers for a flight on a stopover route
        public static int GetStopoverFlightPassengers(FleetAirliner airliner, AirlinerClass.ClassType type)
        {
            RouteTimeTableEntry mainEntry = airliner.CurrentFlight.Entry.MainEntry;
            RouteTimeTableEntry entry = airliner.CurrentFlight.Entry;

            List<Route> legs = mainEntry.TimeTable.Route.Stopovers.SelectMany(s => s.Legs).ToList();

            bool isInbound = mainEntry.DepartureAirport == mainEntry.TimeTable.Route.Destination2;

            int passengers;
            //inboound
            if (isInbound)
            {
                legs.Reverse();
                passengers = GetFlightPassengers(
                    mainEntry.TimeTable.Route.Destination2,
                    mainEntry.TimeTable.Route.Destination1,
                    airliner,
                    type);
            }
            else
            {
                passengers = GetFlightPassengers(
                    mainEntry.TimeTable.Route.Destination1,
                    mainEntry.TimeTable.Route.Destination2,
                    airliner,
                    type);
            }

            int index = legs.IndexOf(entry.TimeTable.Route);

            for (int i = index; i < legs.Count; i++)
            {
                if (isInbound)
                {
                    passengers += GetFlightPassengers(
                        entry.TimeTable.Route.Destination1,
                        legs[i].Destination1,
                        airliner,
                        type);
                }
                else
                {
                    passengers += GetFlightPassengers(
                        entry.TimeTable.Route.Destination1,
                        legs[i].Destination2,
                        airliner,
                        type);
                }
            }

            if (passengers < 0)
            {
                passengers = 0;
            }

            return Math.Min(airliner.Airliner.GetAirlinerClass(type).SeatingCapacity, passengers);
        }
        private void ButtonAdd_Click(object sender, RoutedEventArgs e)
        {
            int seating = (int)((Button)sender).Tag;

              AirlinerClass aClass = new AirlinerClass(this.CurrentClass, seating);

            aClass.ForceSetFacility(this.Classes[0].GetFacility(AirlinerFacility.FacilityType.Audio));
            aClass.ForceSetFacility(this.Classes[0].GetFacility(AirlinerFacility.FacilityType.Seat));
            aClass.ForceSetFacility(this.Classes[0].GetFacility(AirlinerFacility.FacilityType.Video));

            this.Classes.Add(aClass);

            // chs, 2011-11-10 added so seat capacity is correctly calculated
            this.Classes[0].SeatingCapacity -= aClass.SeatingCapacity;
            this.Classes[0].RegularSeatingCapacity -= aClass.SeatingCapacity;

            showAirlinerClasses();
        }
        private static double GetNearbyPassengerDemand(
            Airport airportCurrent,
            Airport airportDestination,
            FleetAirliner airliner,
            AirlinerClass.ClassType type)
        {
            TimeSpan flightTime = MathHelpers.GetFlightTime(airportCurrent, airportDestination, airliner.Airliner.Type);

            double maxDistance = (flightTime.TotalHours*0.5)*100;

            IEnumerable<Airport> nearbyAirports =
                AirportHelpers.GetAirportsNearAirport(airportCurrent, maxDistance)
                              .DefaultIfEmpty()
                              .Where(a => !AirportHelpers.HasRoute(a, airportDestination));

            double demand = 0;

            foreach (Airport airport in nearbyAirports)
            {
                if (airport != null)
                {
                    double distance = MathHelpers.GetDistance(airportCurrent, airport);

                    double airportDemand = airport.GetDestinationPassengersRate(airportDestination, type);

                    if (distance < 150)
                    {
                        demand += airportDemand*0.75;
                    }

                    if (distance >= 150 && distance < 225)
                    {
                        demand += airportDemand*0.5;
                    }

                    if (distance >= 225 && distance < 300)
                    {
                        demand += airportDemand*0.25;
                    }

                    if (distance >= 300 && distance < 400)
                    {
                        demand += airportDemand*0.10;
                    }
                }
            }

            return demand;
        }
Ejemplo n.º 26
0
 //returns the route airliner class for a specific class type
 public RouteAirlinerClass GetRouteAirlinerClass(AirlinerClass.ClassType type)
 {
     return Classes.Find(cl => cl.Type == type);
 }
 public AirlinerFacilityItem( AirlinerClass aClass, AirlinerFacility facility)
 {
     this.AirlinerClass = aClass;
     this.Facility = facility;
 }
Ejemplo n.º 28
0
 public double GetServiceLevel(AirlinerClass.ClassType type)
 {
     return Classes.Find(c => c.Type == type).GetFacilities().Sum(f => f.ServiceLevel);
 }
Ejemplo n.º 29
0
 public double GetFarePrice(AirlinerClass.ClassType type)
 {
     return Classes.Find(c => c.Type == type).FarePrice;
 }
Ejemplo n.º 30
0
        public AirlineClassMVVM(AirlinerClass.ClassType type)
        {
            Type = type;

            Facilities = new List<AirlineClassFacilityMVVM>();
        }