private static string SerializeFleet(Fleet fleet)
     => string.Join(",",
         fleet.Ships.Select(x => string.Concat(
                 "{\"id\":",
                 x.Id,
                 ",\"shipid\":",
                 x.ShipId,
                 ",\"lv\":",
                 x.Level,
                 ",\"karyoku\":",
                 x.Firepower.Current,
                 ",\"raisou\":",
                 x.Torpedo.Current,
                 ",\"taiku\":",
                 x.AA.Current,
                 ",\"soukou\":",
                 x.Armor.Current,
                 ",\"kaihi\":",
                 x.Evasion.Current,
                 ",\"taisen\":",
                 x.ASW.Current,
                 ",\"sakuteki\":",
                 x.LoS.Current,
                 ",\"lucky\":",
                 x.Luck.Current,
                 ",\"slots\":[",
                 string.Join(",", x.Slots.Where(y => y.HasItem).Select(y => EquipToString(y.Item))),
                 "],\"slotex\":",
                 x.SlotEx.HasItem ? EquipToString(x.SlotEx.Item) : "null",
                 "}")
         ));
        internal SortieInfo(long rpID, Fleet rpFleet, int rpMapID)
        {
            ID = rpID;

            Current = this;

            Fleet = rpFleet;
            MainShips = Fleet.Ships.Select(r => new FriendShip(r)).ToList<IParticipant>();

            var rPort = KanColleGame.Current.Port;

            if (rPort.Fleets.CombinedFleetType != 0 && rpFleet.ID == 1)
            {
                EscortFleet = rPort.Fleets[2];
                EscortShips = EscortFleet.Ships.Select(r => new FriendShip(r)).ToList<IParticipant>();
            }

            Map = KanColleGame.Current.Maps[rpMapID];

            if (Map.AvailableAirBaseGroupCount > 0)
            {
                var rAllGroups = rPort.AirBase.Table[Map.MasterInfo.AreaID].Values;

                AirForceGroups = rAllGroups.Take(Map.AvailableAirBaseGroupCount).Where(r => r.Option == AirForceGroupOption.Sortie)
                    .Concat(rAllGroups.Where(r => r.Option == AirForceGroupOption.AirDefense))
                    .ToArray();
            }
        }
Exemple #3
0
    void CreateScoreInfo(Fleet fleet)
    {
        GameObject scoreInfoObj = (GameObject)UnityEngine.GameObject.Instantiate(Resources.Load("ScoreInfo"));
        RectTransform rt = scoreInfoObj.GetComponent<RectTransform> ();
        rt.SetParent (transform);
        rt.localScale = Vector3.one;

        ScoreStat scoreStat = scoreInfoObj.GetComponent<ScoreStat>();
        scoreStat.teamColor.color = fleet.team.color;
        scoreStat.fleetColor.color = fleet.color;
        scoreStat.fleetName.text = fleet.name;
        scoreStat.KillCountEnemyShip.text = GetKillEnemyCount(fleet).ToString();
        scoreStat.DamagePointEnemyShip.text = GetDamagePointEnemy(fleet).ToString();
        scoreStat.KillCountAllyShip.text = GetKillAllyCount(fleet).ToString();
        scoreStat.DamagePointAllyShip.text = GetDamagePointAlly(fleet).ToString();
        scoreStat.TotalDamagePoint.text = GetDamagePointTotal(fleet).ToString();

        RawImage ri = scoreInfoObj.GetComponent<RawImage> ();
        if (IsGameWin (fleet)) {
            ri.color = winColor;
            scoreStat.Result.text = "Win";

        } else {
            ri.color = loseColor;
            scoreStat.Result.text = "Lose";
        }
        // return teamStat;
    }
        internal FleetStatus(Fleet rpOwner)
        {
            r_Fleet = rpOwner;

            FighterPower = new FleetFighterPowerStatus(rpOwner);
            LoS = new FleetLoSStatus(rpOwner);
        }
        internal WhirlpoolEvent(IEnumerable<Ship> rpShips, Fleet rpEscortFleet, RawMapExploration rpData) : base(rpData)
        {
            var rMaxAmount = (double)rpShips.Max(r => LostMaterial == MaterialType.Fuel ? r.Fuel.Current : r.Bullet.Current);
            var rReducedRate = Amount / rMaxAmount;

            var rTotalAmount = 0;

            foreach (var rShip in rpShips)
            {
                int rReducedAmount;

                if (LostMaterial == MaterialType.Fuel)
                {
                    rReducedAmount = (int)(rShip.Fuel.Current * rReducedRate);
                    rShip.Fuel.Current -= rReducedAmount;
                }
                else
                {
                    rReducedAmount = (int)(rShip.Bullet.Current * rReducedRate);
                    rShip.Bullet.Current -= rReducedAmount;
                }

                rTotalAmount += rReducedAmount;
            }

            var rMessage = rpEscortFleet == null ? StringResources.Instance.Main.Sortie_Whirlpool_Message : StringResources.Instance.Main.Sortie_Whirlpool_Message_CombinedFleet;
            Message = string.Format(rMessage, LostMaterial == MaterialType.Fuel ? "[icon]fuel[/icon]" : "[icon]bullet[/icon]", rTotalAmount, rReducedRate);
        }
 public double Calculate(Fleet rpFleet)
 {
     if (rpFleet == null || rpFleet.Ships.Count == 0)
         return 0;
     else
         return CalculateCore(rpFleet);
 }
Exemple #7
0
 public void AddShip(Fleet fleet, IShip ship)
 {
     if (fleet == Fleet.Red)
         redShips.Add(ship);
     else
         blueShips.Add(ship);
 }
        internal ExpeditionResultPrediction(ExpeditionInfo2 rpInfo, Fleet rpFleet)
        {
            r_Info = rpInfo;
            r_Fleet = rpFleet;

            Check();
        }
 public void CenterScreen(Fleet fleet)
 {
     _gameMain.EmpireManager.CurrentEmpire.SelectedFleetGroup = new FleetGroup(new List<Fleet> { fleet });
     _gameMain.EmpireManager.CurrentEmpire.SelectedSystem = null;
     _camera.CenterCamera((int)fleet.GalaxyX, (int)fleet.GalaxyY, _camera.ZoomDistance);
     _fleetView.LoadFleetGroup(_gameMain.EmpireManager.CurrentEmpire.SelectedFleetGroup);
 }
 /// <summary>
 /// Determine what the real threat of the opposing fleet is. The Higher the value the more chance (myfleet) has to win.
 /// > 20 Solo Engage
 /// -20 -> 20 Team Engage
 /// < -20 Last Resort
 /// </summary>
 /// <returns>Determined .</returns>
 /// <param name="myFleet">My fleet.</param>
 /// <param name="enemytFleet">Enemy fleet.</param>
 public static float RealThreatDeterminer(Fleet myFleet, Fleet enemyFleet)
 {
     ////Debug.Log("Fleet 1 Threat: " + forFleet.threat + " / Fleet 2 Threat: " + againstFleet.threat);
     int relations = FactionTracker.Instance.GetRelationFor(myFleet.faction, enemyFleet.faction);
     // 30 - 50 + 5 = -25
     float realThreat = myFleet.threat - relations + enemyFleet.threat;
     return realThreat;
 }
 private void PopulateFleet(Fleet fleet, ShipFactory shipFactory)
 {
     // fill the battlefield with an appropriate number of ships on each side.
     for (int i = 0; i < shipCount; i++)
     {
         field.AddShip(fleet, shipFactory.CreateRandomShip());
     }
 }
Exemple #12
0
 void Start()
 {
     damageBehavior = GetComponent<DamageBehavior>();
     bodySprite = transform.Find ("Body").GetComponent<SpriteRenderer>();
     bullets = GameObject.Find ("Game Root/Bullets");
     fleet = GetComponent<Entity>().affinity.GetComponent<Fleet>();
     bulletPrefab = Resources.Load ("Bullet") as GameObject;
 }
        protected override double CalculateCore(Fleet rpFleet)
        {
            var rShipLoS = .0;
            var rEquipmentLoS = .0;

            foreach (var rShip in rpFleet.Ships.ExceptEvacuated())
            {
                var rShipLoSBase = (double)rShip.Status.LoS;

                foreach (var rSlot in rShip.Slots.Where(r => r.HasEquipment))
                {
                    var rInfo = rSlot.Equipment.Info;
                    var rLoS = (double)rInfo.LoS;
                    rShipLoSBase -= rLoS;

                    switch (rInfo.Type)
                    {
                        case EquipmentType.CarrierBasedDiveBomber:
                            rEquipmentLoS += rLoS * 1.0376255;
                            break;

                        case EquipmentType.CarrierBasedTorpedoBomber:
                            rEquipmentLoS += rLoS * 1.3677954;
                            break;

                        case EquipmentType.CarrierBasedRecon:
                            rEquipmentLoS += rLoS * 1.6592780;
                            break;

                        case EquipmentType.ReconSeaplane:
                            rEquipmentLoS += rLoS * 2.0;
                            break;

                        case EquipmentType.SeaplaneBomber:
                            rEquipmentLoS += rLoS * 1.7787282;
                            break;

                        case EquipmentType.SmallRadar:
                            rEquipmentLoS += rLoS * 1.0045358;
                            break;

                        case EquipmentType.LargeRadar:
                            rEquipmentLoS += rLoS * 0.9906638;
                            break;

                        case EquipmentType.Searchlight:
                            rEquipmentLoS += rLoS * 0.9067950;
                            break;
                    }
                }

                rShipLoS += Math.Sqrt(rShipLoSBase) * 1.6841056;
            }

            var rAdmiralLoS = Math.Ceiling(rpFleet.Port.Admiral.Level / 5.0) * 5.0 * 0.6142467;

            return rShipLoS + rEquipmentLoS - rAdmiralLoS;
        }
Exemple #14
0
 public Fleet(Fleet f)
 {
     owner = f.owner;
     numShips = f.numShips;
     sourcePlanet = f.sourcePlanet;
     destinationPlanet = f.destinationPlanet;
     totalTripLength = f.totalTripLength;
     turnsRemaining = f.turnsRemaining;
 }
 private Fleet(Fleet f)
 {
     _owner = f._owner;
     _numShips = f._numShips;
     _sourcePlanet = f._sourcePlanet;
     _destinationPlanet = f._destinationPlanet;
     _totalTripLength = f._totalTripLength;
     _turnsRemaining = f._turnsRemaining;
 }
Exemple #16
0
 //private int owner;
 //private int numShips;
 //private int sourcePlanet;
 //private int destinationPlanet;
 //private int totalTripLength;
 //private int turnsRemaining;
 private Fleet(Fleet _f)
 {
     Owner = _f.Owner;
     NumShips = _f.NumShips;
     SourcePlanet = _f.SourcePlanet;
     DestinationPlanet = _f.DestinationPlanet;
     TotalTripLength = _f.TotalTripLength;
     TurnsRemaining = _f.TurnsRemaining;
 }
Exemple #17
0
 void Start()
 {
     fleet = GetComponent<Entity>().affinity.GetComponent<Fleet>();
     damageBehavior = GetComponent<DamageBehavior>();
     transform.Find ("Sentry").GetComponent<Entity>().affinity = GetComponent<Entity>().affinity;
     transform.Find ("Body").GetComponent<SpriteRenderer>().color = fleet.teamColor;
     coreSentry = transform.Find ("Sentry").GetComponent<CoreSentry>();
     coreSentry.core = this;
 }
Exemple #18
0
 float GetDamagePointTotal(Fleet fleet)
 {
     float totalDamage = 0;
     foreach (KeyValuePair<Fleet, float> victimFleet in Record.damageInfo[fleet])
     {
         totalDamage += victimFleet.Value;
     }
     return totalDamage;
 }
Exemple #19
0
    //Add dummy data, should load the player's actual fleets from the database on load.
    void Start()
    {
        Fleet testFleet = new Fleet("MiningFleet 1");
        testFleet.AddShip(new Ship(0,0));
        fleets.Add(testFleet);

        //Should load a player's actual items from the database on load
        items.Add(new Item(0,0,1,"Minerals"));
    }
 private Fleet(Fleet _f)
 {
     owner = _f.owner;
     numShips = _f.numShips;
     sourcePlanet = _f.sourcePlanet;
     destinationPlanet = _f.destinationPlanet;
     totalTripLength = _f.totalTripLength;
     turnsRemaining = _f.turnsRemaining;
 }
        internal SortieInfo(Fleet rpFleet, int rpMapID)
        {
            r_Current = this;

            Fleet = rpFleet;
            if (KanColleGame.Current.Port.Fleets.CombinedFleetType != 0 && rpFleet.ID == 1)
                EscortFleet = KanColleGame.Current.Port.Fleets[2];

            Map = KanColleGame.Current.Maps[rpMapID];
        }
Exemple #22
0
 float GetDamagePointEnemy(Fleet fleet)
 {
     float totalDamage = 0;
     foreach (KeyValuePair<Fleet, float> victimFleet in Record.damageInfo[fleet])
     {
         if (fleet.team != victimFleet.Key.team)
             totalDamage += victimFleet.Value;
     }
     return totalDamage;
 }
Exemple #23
0
 int GetKillAllyCount(Fleet fleet)
 {
     int totalCount = 0;
     foreach (KeyValuePair<Fleet, float> victimFleet in Record.killInfo[fleet])
     {
         if (fleet.team == victimFleet.Key.team)
             totalCount += (int)victimFleet.Value;
     }
     return totalCount;
 }
Exemple #24
0
 public static void Kill(Fleet killer,Fleet victim)
 {
     killInfo [killer] [victim]++;
     if (killer.team != victim.team) {
         killEnemy[killer.team]++;
     } else {
         killAlly[killer.team]++;
     }
     _ui.UpdateTeamStat (killer.team, killAlly [killer.team], killEnemy [killer.team]);
 }
        protected override double CalculateCore(Fleet rpFleet)
        {
            var rResult = .0;

            foreach (var rShip in rpFleet.Ships.ExceptEvacuated())
            {
                var rShipLoS = rShip.Status.LoS;
                var rEquipmentLoS = .0;

                foreach (var rSlot in rShip.Slots.Where(r => r.HasEquipment))
                {
                    var rInfo = rSlot.Equipment.Info;
                    var rLoS = (double)rInfo.LoS;
                    rShipLoS -= rInfo.LoS;

                    switch (rInfo.Type)
                    {
                        case EquipmentType.CarrierBasedDiveBomber:
                            rEquipmentLoS += rLoS * .6;
                            break;

                        case EquipmentType.CarrierBasedTorpedoBomber:
                            rEquipmentLoS += rLoS * .8;
                            break;

                        case EquipmentType.CarrierBasedRecon:
                            rEquipmentLoS += rLoS;
                            break;

                        case EquipmentType.ReconSeaplane:
                            rEquipmentLoS += rLoS * 1.2;
                            break;

                        case EquipmentType.SeaplaneBomber:
                            rEquipmentLoS += rLoS;
                            break;

                        case EquipmentType.SmallRadar:
                        case EquipmentType.LargeRadar:
                            rEquipmentLoS += rLoS * .6;
                            break;

                        default:
                            rEquipmentLoS += rLoS * .5;
                            break;
                    }
                }

                rResult += Math.Floor(Math.Sqrt(rShipLoS) + rEquipmentLoS);
            }

            rResult -= Math.Floor(rpFleet.Port.Admiral.Level * .4);

            return rResult;
        }
        internal FleetExpeditionStatusViewModel(Fleet rpFleet)
        {
            r_Fleet = rpFleet;
            r_Source = rpFleet.ExpeditionStatus;

            PropertyChangedEventListener.FromSource(r_Source).Add(nameof(r_Source.Expedition), (s, e) => UpdateExpeditionYield());
            UpdateExpeditionYield();

            Observable.FromEventPattern<PropertyChangedEventArgs>(r_Source, nameof(r_Source.PropertyChanged))
                .Select(r => r.EventArgs.PropertyName).Subscribe(OnPropertyChanged);
        }
        protected override double CalculateCore(Fleet rpFleet)
        {
            var rShipLoS = .0;
            var rShipCount = 0;
            var rEquipmentLoS = .0;

            foreach (var rShip in rpFleet.Ships.ExceptEvacuated())
            {
                var rShipLoSBase = rShip.Status.LoS;
                rShipCount++;

                foreach (var rSlot in rShip.Slots.Where(r => r.HasEquipment))
                {
                    var rInfo = rSlot.Equipment.Info;
                    var rLoS = (double)rInfo.LoS;
                    rShipLoSBase -= rInfo.LoS;

                    switch (rInfo.Type)
                    {
                        case EquipmentType.CarrierBasedTorpedoBomber:
                            rEquipmentLoS += rLoS * .8;
                            break;

                        case EquipmentType.CarrierBasedRecon:
                            rEquipmentLoS += rLoS;
                            break;

                        case EquipmentType.ReconSeaplane:
                            rEquipmentLoS += (rLoS + Math.Sqrt(rSlot.Equipment.Level) * 1.2) * 1.2;
                            break;

                        case EquipmentType.SeaplaneBomber:
                            rEquipmentLoS += rLoS * 1.1;
                            break;

                        case EquipmentType.SmallRadar:
                        case EquipmentType.LargeRadar:
                            rEquipmentLoS += (rLoS + Math.Sqrt(rSlot.Equipment.Level) * 1.25) * .6;
                            break;

                        default:
                            rEquipmentLoS += rLoS * .6;
                            break;
                    }
                }

                rShipLoS += Math.Sqrt(rShipLoSBase);
            }

            var rAdmiralLoS = Math.Ceiling(rpFleet.Port.Admiral.Level * .4);
            var rEmptyShipslotBonus = (6 - rShipCount) * 2;

            return rShipLoS + rEquipmentLoS - rAdmiralLoS + rEmptyShipslotBonus;
        }
Exemple #28
0
 public void ReportDestroy(Fleet fleet)
 {
     destroyedfleetcount++;
     if (_fleets.Count == destroyedfleetcount)
     {
         if (fleet.destroyedByTimePenalty)
             this.destroyedByTimePenalty = true;
         Debug.Log ("Team destroyed Time Penalty : True");
         Match.ReportDestroy(fleet.team);
     }
 }
Exemple #29
0
 void Update()
 {
     if(fleet == null) {
         fleet = GetFleet();
         meterRatio = 1;
     }else{
         meterRatio = fleet.CurrentHealthRatio();
     //			dangerText.gameObject.SetActive(meterRatio <= 0.1f);
     //			coreText.gameObject.SetActive(meterRatio > 0.1f);
     }
     filler.localScale = new Vector3(meterRatio, 1, 1);
 }
        static void Main(string[] args)
        {
            var grid = new Grid(10, 10);

            var fleet = new Fleet(new List<Ship>
            {
                new Ship(ShipType.Battleship, ShipOrientation.Horizontal, grid.Width, grid.Height),
                new Ship(ShipType.Destroyer, ShipOrientation.Vertical, grid.Width, grid.Height),
                new Ship(ShipType.Destroyer, ShipOrientation.Horizontal, grid.Width, grid.Height)
            });

            grid.PlaceShipsOnGrid(fleet);
        }
Exemple #31
0
 public void SetFleet(Fleet fleet)
 {
     this.fleet = fleet;
 }
    // Coroutine to randomly spawn the waves
    IEnumerator SpawnWaves()
    {
        yield return(new WaitForSeconds(0.5f));

        while (true)
        {
            if (Level.Ships.Count > 0)
            {
                firstShip       = Level.Ships [0];
                timeToSpawnShip = firstShip.zPos / 4;
            }
            else
            {
                timeToSpawnShip = 1000;
            }
            if (Level.Asteroids.Count > 0)
            {
                firstAsteroid       = Level.Asteroids [0];
                timeToSpawnAsteroid = firstAsteroid.zPos / 4;
            }
            else
            {
                timeToSpawnAsteroid = 1000;
            }
            if (Level.Fleets.Count > 0)
            {
                firstFleet       = Level.Fleets [0];
                timeToSpawnFleet = firstFleet.zPos / 4;
            }
            else
            {
                timeToSpawnFleet = 1000;
            }

            if (timeToSpawnShip <= timeToSpawnAsteroid && timeToSpawnShip <= timeToSpawnFleet)
            {
                timeToSpawn     = timeToSpawnShip;
                firstObjectType = 0;
            }
            else if (timeToSpawnAsteroid <= timeToSpawnShip && timeToSpawnAsteroid <= timeToSpawnFleet)
            {
                timeToSpawn     = timeToSpawnAsteroid;
                firstObjectType = 1;
            }
            else if (timeToSpawnFleet <= timeToSpawnAsteroid && timeToSpawnFleet <= timeToSpawnShip)
            {
                timeToSpawn     = timeToSpawnFleet;
                firstObjectType = 2;
            }
            if (time < timeToSpawn)
            {
                yield return(new WaitForSeconds(timeToSpawn - time));
            }
            // Instantiates the hazard at a set z value for position and the corresponding x value from the editor
            // In the editor the x goes from 0 to -12 and in the Load Level and arcade it goes from -6 to 6, hence the +6 on the x position
            // After it instantiates the hazard, it flags it to be removed from the list
            else if (time >= timeToSpawn)
            {
                if (firstObjectType == 0)
                {
                    switch (firstShip.type)
                    {
                    case "Grunt":
                        loadedObject  = Ships [0];
                        spawnRotation = Quaternion.Euler(0, 0, 330);
                        break;

                    case "Vector":
                        loadedObject  = Ships [1];
                        spawnRotation = Quaternion.Euler(0, 0, 330);
                        break;
                    }
                    spawnPosition = new Vector3(0, firstShip.yPos, 30);
                }
                else if (firstObjectType == 1)
                {
                    switch (firstAsteroid.type)
                    {
                    case "Asteroid_small":
                        loadedObject = Asteroids [0];
                        break;

                    case "Asteroid_Medium":
                        loadedObject = Asteroids [1];
                        break;

                    case "Asteroid_Big":
                        loadedObject = Asteroids [2];
                        break;
                    }
                    spawnRotation = Quaternion.identity;
                    spawnPosition = new Vector3(0, firstAsteroid.yPos, 30);
                }
                else
                {
                    switch (firstFleet.type)
                    {
                    case "Block_Formation":
                        loadedObject = Fleets [0];
                        break;

                    case "Triangle_Formation":
                        loadedObject = Fleets [1];
                        break;

                    case "Row_Formation":
                        loadedObject = Fleets [2];
                        break;
                    }
                    spawnRotation = Quaternion.identity;
                    spawnPosition = new Vector3(0, firstFleet.yPos, 30);
                }
                instancedObject = Instantiate(loadedObject, spawnPosition, spawnRotation) as GameObject;

                if (firstObjectType == 0)
                {
                    shipScript          = instancedObject.GetComponent <ShipBehaviour> ();
                    shipScript.speed    = firstShip.speed;
                    shipScript.movement = firstShip.movement;
                    shipScript.special  = firstShip.special;
                }
                else if (firstObjectType == 2)
                {
                    formationScript          = instancedObject.GetComponent <FormationScriptArcade> ();
                    formationScript.speed    = firstFleet.speed;
                    formationScript.movement = firstFleet.movement;
                    formationScript.special  = firstFleet.special;
                    formationScript.ship     = firstFleet.ship_type;
                }

                remove = true;
            }
            // Removes the instantiated hazard
            if (remove)
            {
                if (firstObjectType == 0 && Level.Ships.Count > 0)
                {
                    Level.Ships.RemoveAt(0);
                    remove = false;
                }
                else if (firstObjectType == 1 && Level.Asteroids.Count > 0)
                {
                    Level.Asteroids.RemoveAt(0);
                    remove = false;
                }
                else if (firstObjectType == 2 && Level.Fleets.Count > 0)
                {
                    Level.Fleets.RemoveAt(0);
                    remove = false;
                }
            }
            // If there are no more Hazards in the list, then instantiate boss
            if (Level.Ships.Count == 0 && Level.Asteroids.Count == 0 && Level.Fleets.Count == 0)
            {
                yield return(new WaitForSeconds(4));

                Vector3 spawnBoss = new Vector3(spawnBossValues.x, spawnBossValues.y, spawnBossValues.z);
                if (Level.Boss == "Goliath")
                {
                    myBoss = boss1;
                }
                if (Level.Boss == "Red Flash")
                {
                    myBoss = boss2;
                }
                Instantiate(myBoss, spawnBoss, Quaternion.identity);
                break;
            }
            // If the player is Destroyed, stops the Coroutine
            if (gameOver)
            {
                break;
            }
        }
    }
Exemple #33
0
 private static string GetNightContact(Fleet fleet)
 {
     return(fleet.NightContactTriggerRate > 0 ? $"夜偵:{fleet.NightContactTriggerRate}%" : "");
 }
 private bool canTransferFleet(Fleet currentFleet, Fleet fleetToMergeInto)
 {
     return(fleetToMergeInto.getAllegiance() == currentFleet.getAllegiance() && !fleetToMergeInto.isInTransit());
 }
Exemple #35
0
 public void FireFrom(Fleet fleet)
 {
     fleet.Owner?.SetInvulnerability(fleet.World.Hook.SpawnInvulnerabilityTime, true);
 }
Exemple #36
0
        /// <summary>
        /// 基地航空隊を敵艦隊にぶつけた際のシミュレーションを行う
        /// (シミュレーション対象:St1まで)
        /// </summary>
        /// <param name="friend">基地航空隊の情報</param>
        /// <param name="enemy">敵艦隊の情報</param>
        /// <param name="simulationCount">試行回数</param>
        /// <param name="finalAAV">敵の最終制空値を、制空値=>確率で表現したもの</param>
        /// <param name="awsCount">制空状況のカウント。[航空隊番号][攻撃回数][各制空状態]</param>
        public void BasedAirUnitSimulation(
            BasedAirUnitGroup friend,
            Fleet enemy,
            int simulationCount,
            out Dictionary <int, double> finalAAV,
            out List <List <List <int> > > awsCount)
        {
            // 出力先を準備する
            finalAAV = new Dictionary <int, double>();
            awsCount = new List <List <List <int> > >();
            for (int si = 0; si < friend.BasedAirUnitList.Count; ++si)
            {
                var basedAirUnit = friend.BasedAirUnitList[si];
                var temp1        = new List <List <int> >();
                for (int ci = 0; ci < basedAirUnit.SallyCount; ++ci)
                {
                    var temp2 = new List <int> {
                        0, 0, 0, 0, 0
                    };
                    temp1.Add(temp2);
                }
                awsCount.Add(temp1);
            }

            // 「基地航空隊の制空値を記録した配列」を事前に準備する
            var friendAntiAirValue = new List <int>();

            for (int si = 0; si < friend.BasedAirUnitList.Count; ++si)
            {
                friendAntiAirValue.Add(CalcAntiAirValue(friend.BasedAirUnitList[si].WeaponList, friend.SlotList[si], true));
            }

            // シミュレーションを行う
            for (int li = 0; li < simulationCount; ++li)
            {
                // 基地航空隊・敵艦隊のデータから、スロット毎の搭載数を読み取る
                var enemySlotData = enemy.SlotList;

                // 指定した回数だけ基地航空隊をぶつける
                for (int si = 0; si < friend.BasedAirUnitList.Count; ++si)
                {
                    var basedAirUnit = friend.BasedAirUnitList[si];
                    for (int ci = 0; ci < basedAirUnit.SallyCount; ++ci)
                    {
                        // 敵艦隊の制空値を計算する
                        int enemyAntiAirValue = CalcAntiAirValue(enemy, enemySlotData, true);

                        // 制空状況を判断する
                        var airWarStatus = JudgeAirWarStatus(friendAntiAirValue[si], enemyAntiAirValue);
                        ++awsCount[si][ci][(int)airWarStatus];

                        // St1撃墜を行う
                        LostEnemySlotBySt1(enemy, ref enemySlotData, airWarStatus);
                    }
                }

                // 最終制空値を読み取る
                int aav = CalcAntiAirValue(enemy, enemySlotData, false);
                if (finalAAV.ContainsKey(aav))
                {
                    ++finalAAV[aav];
                }
                else
                {
                    finalAAV[aav] = 1;
                }
            }

            // この段階では、finalAAVの値が「制空値=>それになった回数」となっており、また制空値でソートされていない。
            // そこで、LINQを使って制空値キーでソートし、また「制空値=>それになった確率」と構築し直す
            finalAAV = finalAAV.OrderBy((x) => x.Key).ToDictionary(pair => pair.Key, pair => pair.Value / simulationCount);
        }
Exemple #37
0
 void Start()
 {
     fleet = CreateFleet(Units, FleetOwner, FleetName);
     fleet.SortBySize();
     DeployFleet(fleet, Vector3.zero);
 }
Exemple #38
0
 public void Deconstruct(out Fleet fleet, out bool hasShips)
 {
     fleet    = Fleet;
     hasShips = HasShips;
 }
Exemple #39
0
    public IEnumerator BeginGame()
    {
        timerText.GetComponentInChildren <Text>().text = "00:00";
        while (true)
        {
            if (session.areAllShipsPlaced())
            {
                break;
            }
            yield return(null);
        }
        //this will happen only when all ships are placed.

        session.startGame();
        StartCoroutine(updateTimer());

        yield return(addPlayerToFirebase());

        battlefleet = new Fleet(allships);

        yield return(dbScript.saveShips(this, battlefleet));

        //start the turns.
        if (starts)
        {
            session.isMyTurn = true;
            while (true)
            {
                if (session.isMyTurn)
                {
                    //         Debug.Log("my turn!");
                    yield return(null);
                }
                else
                {
                    //          Debug.Log("their turn!");
                    yield return(null);
                }
            }
        }
        else
        {
            while (true)
            {
                if (session.isMyTurn)
                {
                    //            Debug.Log("nmy turn!");
                    yield return(null);
                }
                else
                {
                    //           Debug.Log("ntheir turn!");
                    yield return(null);
                }
            }
        }



        yield return(null);
    }
Exemple #40
0
 public FleetOperational(Fleet fleet, bool hasShips)
 {
     Fleet    = fleet;
     HasShips = hasShips;
 }
        private void ProcessMessage(byte [] data)
        {
            //Deserialize message
            IFormatter   fmt       = new BinaryFormatter();
            MemoryStream memHolder = new MemoryStream(data, 0, data.Length);

            memHolder.Position = 0;
            switch (_msgType)
            {
            case MsgType.Ping:
            {
                Console.WriteLine("Pong");
                break;
            }

            case MsgType.Text:
            {
                MsgText msg = (MsgText)fmt.Deserialize(memHolder);
                //if this is the first message assign it to client name
                if (_firstTime)
                {
                    _userName  = msg.Text;
                    _firstTime = false;
                    _connected = true;
                    if (eConnected != null)
                    {
                        EventArgs e = new EventArgs();
                        eConnected(this, e);
                    }
                }
                else if (eMessageReceived != null && _connected)
                {
                    //Else raise the MessageReceived Event
                    //and pass the message along
                    MessageEventArgs e = new MessageEventArgs(msg);
                    eMessageReceived(this, e);
                }
                break;
            }

            case MsgType.Orders:
            {
                //
                //	TODO: make sure it isn't possible to get more
                //     than one set of orders in the list for a
                //		single player
                //

                //accept fleet data from player and add to
                //arraylist of fleetdata
                if (_fleet != null && _orders.Contains(_fleet))
                {
                    Console.WriteLine("Old fleet orders removed for player " + this._clientID);
                    _orders.Remove(_fleet);
                }
                Console.WriteLine("Attempting to Deserialize Orders from player");
                this._fleet = (Fleet)fmt.Deserialize(memHolder);
                ClientHost._orders.Add(_fleet);
                Console.WriteLine("Fleet added to server orders");
                this._ready = true;
                if (eReady != null)
                {
                    EventArgs e = new EventArgs();
                    eReady(this, e);
                }
                break;
            }

            case MsgType.Cancel:
            {
                ClientHost._orders.Remove(this._fleet);
                Console.WriteLine("Fleet orders removed for player " + this._clientID);
                this._ready = false;
                break;
            }

            case MsgType.PlayerIDRequest:
            {
                NameAndID nameAndID = (NameAndID)fmt.Deserialize(memHolder);
                int       id        = nameAndID.ID;
                string    password  = nameAndID.Password;
                if (eIDRequest != null)
                {
                    Console.WriteLine(_userName + " requests player ID(event fired)");
                    IDRequestEventArgs e = new IDRequestEventArgs(id, password);
                    eIDRequest(this, e);
                }
                break;
            }

            case MsgType.SystemName:
            {
                MsgSystemName sysName = (MsgSystemName)fmt.Deserialize(memHolder);
                if (this.eRenameSystem != null)
                {
                    SystemNameEventArgs mea = new SystemNameEventArgs(sysName);
                    this.eRenameSystem(this, mea);
                }
                break;
            }

            case MsgType.Trade:
            {
                MsgTrade tradeMsg = (MsgTrade)fmt.Deserialize(memHolder);
                if (this.eTradeMessage != null)
                {
                    TradeMessageEventArgs ea = new TradeMessageEventArgs(tradeMsg);
                    this.eTradeMessage(this, ea);
                }
                break;
            }
            }
            memHolder.Close();
            //Determine message type
            //Carry out message instructions
        }
        public void UpdateTradeMsg(MsgTrade tradeMsg)
        {
            this._tradeMsg = tradeMsg;
            switch (tradeMsg.Type)
            {
            case MsgTrade.TradeMsgType.Accept:
            {
                this._client.SetUpTrade(tradeMsg.Trade, this.ActivePlayerID);
                this.listBox1.Items.Add(tradeMsg.Trade);
                this.chatBox.AppendText("\r\nTrade agreement confirmed");
                break;
            }

            case MsgTrade.TradeMsgType.Reject:
            {
                this.chatBox.AppendText(tradeMsg.Msg);
                Console.WriteLine("Rejection received");
                break;
            }

            case MsgTrade.TradeMsgType.Message:
            {
                this.chatBox.AppendText(tradeMsg.Msg);
                break;
            }

            case MsgTrade.TradeMsgType.Offer:
            {
                Trade trade = tradeMsg.Trade;
                this.offerMineral.Value  = trade.AskedMineral;
                this.offerOrganic.Value  = trade.AskedOrganic;
                this.offerEnergy.Value   = trade.AskedEnergy;
                this.returnMineral.Value = trade.OfferedMineral;
                this.returnOrganic.Value = trade.OfferedOrganic;
                this.returnEnergy.Value  = trade.OfferedEnergy;
                this.bnAccept.Enabled    = true;
                this.bnReject.Enabled    = true;
                this.bnCancel.Enabled    = false;
                this.bnOffer.Enabled     = false;
                break;
            }

            case MsgTrade.TradeMsgType.Cancel:
            {
                this.listBox1.Items.Clear();
                this.bnCancel.Enabled = false;
                Fleet fleet = _gameData.PlayerList[_thisPlayerID].Fleet;
                for (int i = 0; i < fleet.Count; i++)
                {
                    if (fleet[i].Type == Ship.ShipType.Trader)
                    {
                        Trader trader = (Trader)fleet[i];
                        this.listBox1.Items.Add(trader.Trade);
                    }
                }
                this.chatBox.AppendText("\r\nTrade canceled");
                Console.WriteLine("Cancel message received by dialog box");
                int newExMin = this._exEng + (int)this.returnMineral.Value - (int)this.offerMineral.Value;
                this.surplusEnergy.Text = newExMin.ToString();
                int newExOrg = this._exOrg + (int)this.returnOrganic.Value - (int)this.offerOrganic.Value;
                this.surplusEnergy.Text = newExOrg.ToString();
                int newExEng = this._exEng + (int)this.returnEnergy.Value - (int)this.offerEnergy.Value;
                this.surplusEnergy.Text = newExEng.ToString();
                break;
            }
            }
        }
Exemple #43
0
 public CreateFleetCommand(Fleet fleet, Sector sector)
     : base(Empire.Current)
 {
     Fleet  = fleet;
     Sector = sector;
 }
Exemple #44
0
        /// <summary>
        /// Deal with any fleet battles. How the battle engine in Stars! works is
        /// documented in the Stars! FAQ (a copy is included in the documentation).
        /// </summary>
        public void Run()
        {
            // Determine the positions of any potential battles. For a battle to
            // take place 2 or more fleets must be at the same location.

            List <List <Fleet> > potentialBattles = DetermineCoLocatedFleets();

            // If there are no co-located fleets then there are no fleets at all
            // so there is nothing more to do so we can give up here.

            if (potentialBattles.Count == 0)
            {
                return;
            }

            // Eliminate potential battle locations where there is only one race
            // present.

            List <List <Fleet> > engagements = EliminateSingleRaces(potentialBattles);

            // Again this could result in an empty array. If so, give up here.

            if (engagements.Count == 0)
            {
                return;
            }

            // We now have a list of every collection of fleets of more than one
            // race at the same location. Run through each possible combat zone,
            // build the fleet stacks and invoke the battle at each location
            // between any enemies.

            foreach (List <Fleet> battlingFleets in engagements)
            {
                List <Stack> battlingStacks = GenerateStacks(battlingFleets);

                // If no targets get selected (for whatever reason) then there is
                // no battle so we can give up here.

                if (SelectTargets(battlingStacks) == 0)
                {
                    return;
                }

                stackId = 0;
                Fleet sample = battlingFleets.First() as Fleet;

                if (sample.InOrbit != null)
                {
                    battle.Location = sample.InOrbit.Name;
                }
                else
                {
                    battle.Location = "coordinates " + sample.Position.ToString();
                }

                PositionStacks(battlingStacks);

                // Copy the full list of stacks into the battle report. We need a
                // full list to start with as the list in the battle engine will
                // get depleted during the battle and may not (and most likely will
                // not) be fully populated by the time we Serialize the
                // report. Ensure we take a copy at this point as the "real" stack
                // will mutate as processing proceeds and even ships may vanish.

                foreach (Stack stack in battlingStacks)
                {
                    battle.Stacks[stack.Key] = new Stack(stack);
                }

                DoBattle(battlingStacks);

                ReportBattle();
            }
        }
Exemple #45
0
        /// <Summary>
        /// Update all the fields in the planet Detail display.
        /// </Summary>
        private void UpdateFields()
        {
            if (selectedStar == null)
            {
                return;
            }

            productionQueue.Populate(selectedStar);

            Defenses.ComputeDefenseCoverage(selectedStar);

            defenseType.Text     = selectedStar.DefenseType;
            defenses.Text        = selectedStar.Defenses.ToString(System.Globalization.CultureInfo.InvariantCulture);
            defenseCoverage.Text = Defenses.SummaryCoverage.ToString(System.Globalization.CultureInfo.InvariantCulture);

            factories.Text = selectedStar.Factories.ToString(System.Globalization.CultureInfo.InvariantCulture)
                             + " of " +
                             selectedStar.GetOperableFactories().ToString(System.Globalization.CultureInfo.InvariantCulture);
            mines.Text = selectedStar.Mines.ToString(System.Globalization.CultureInfo.InvariantCulture)
                         + " of " + selectedStar.GetOperableMines().ToString(System.Globalization.CultureInfo.InvariantCulture);
            population.Text = selectedStar.Colonists.ToString(System.Globalization.CultureInfo.InvariantCulture);

            resourceDisplay.ResourceRate = selectedStar.GetResourceRate();

            if (selectedStar.OnlyLeftover == false)
            {
                resourceDisplay.ResearchBudget = empireState.ResearchBudget;
            }
            else
            {
                // We treat Stars contributing only leftover resources as having
                // a 0% budget allocation.

                resourceDisplay.ResearchBudget = 0;
            }

            resourceDisplay.Value = selectedStar.ResourcesOnHand;

            scannerRange.Text = selectedStar.ScanRange.ToString(System.Globalization.CultureInfo.InvariantCulture);
            scannerType.Text  = selectedStar.ScannerType;

            if (selectedStar.Starbase == null)
            {
                starbasePanel.Text    = "No Starbase";
                starbasePanel.Enabled = false;
            }
            else
            {
                Fleet starbase = selectedStar.Starbase;
                starbaseArmor.Text    = starbase.TotalArmorStrength.ToString(System.Globalization.CultureInfo.InvariantCulture);
                starbaseCapacity.Text =
                    starbase.TotalDockCapacity.ToString(System.Globalization.CultureInfo.InvariantCulture);
                starbaseDamage.Text   = "0";
                starbasePanel.Enabled = true;
                starbasePanel.Text    = starbase.Name;
                starbaseShields.Text  = starbase.TotalShieldStrength.ToString();

                massDriverType.Text        = "None";
                massDriverDestination.Text = "None";
                targetButton.Enabled       = false;
            }

            List <string> fleetnames = new List <string>();

            fleetsInOrbit = new Dictionary <string, Fleet>();
            foreach (Fleet fleet in empireState.OwnedFleets.Values)
            {
                if (fleet.InOrbit != null && fleet.InOrbit.Name == selectedStar.Name && !fleet.IsStarbase)
                {
                    fleetnames.Add(fleet.Name);
                    fleetsInOrbit[fleet.Name] = fleet;
                }
            }
            fleetnames.Sort();
            comboFleetsInOrbit.Items.Clear();
            bool haveFleets = fleetnames.Count > 0;

            if (haveFleets)
            {
                comboFleetsInOrbit.Items.AddRange(fleetnames.ToArray());
                comboFleetsInOrbit.SelectedIndex = 0;
            }
            buttonGoto.Enabled = haveFleets;
            buttonGoto.Enabled = haveFleets;
        }
Exemple #46
0
        public void FirstBattleTest()
        {
            WeaponModel xLaser = new WeaponModel()
            {
                ID          = "xLaser",
                Name        = "Taim & Bak KX9 laser cannon",
                Damage      = 10,
                Accuracy    = 1,
                Capacity    = 0,
                ReloadTimer = 1
            };
            WeaponModel tLaser = new WeaponModel()
            {
                ID          = "tLaser",
                Name        = "L-s1 laser cannon",
                Damage      = 10,
                Accuracy    = 1,
                Capacity    = 0,
                ReloadTimer = 1
            };
            WeaponModel torpedo = new WeaponModel()
            {
                ID          = "torpedo",
                Name        = "Krupx MG7 proton torpedo launcher",
                Damage      = 10,
                Accuracy    = 1,
                Capacity    = 3,
                ReloadTimer = 10
            };

            ShipModel xWingModel = new ShipModel()
            {
                ID               = "xwing",
                Name             = "T-65 X-Wing Starfighter",
                Class            = ShipClass.Fighter,
                OffensiveWeapons = new List <WeaponModel>()
                {
                    xLaser, xLaser, xLaser, xLaser, torpedo, torpedo
                },
                Shields      = 100,
                HullStrength = 100
            };
            ShipModel tieModel = new ShipModel()
            {
                ID               = "tie",
                Name             = "TIE/LN Starfighter",
                Class            = ShipClass.Fighter,
                OffensiveWeapons = new List <WeaponModel>()
                {
                    tLaser, tLaser
                },
                Shields      = 0,
                HullStrength = 100
            };

            Ship xWing = new Ship()
            {
                ID    = "xWing",
                Name  = "X-Wing",
                Model = xWingModel,
            };
            Ship tie = new Ship()
            {
                ID    = "tie",
                Name  = "TIE Fighter",
                Model = tieModel,
            };

            Fleet rebelFleet = new Fleet();

            rebelFleet.Ships.Add(xWing);
            Fleet impFleet = new Fleet();

            impFleet.Ships.Add(tie);

            BattleFleet rebels = new BattleFleet(rebelFleet);
            BattleFleet imps   = new BattleFleet(impFleet);

            rebels.Reset();
            rebels.Attack(imps);
        }
Exemple #47
0
 internal FleetMovedNotification(Fleet fleet)
 {
     Fleet = fleet;
 }
Exemple #48
0
        public static void Main(string[] args)
        {
            if (!Directory.Exists("../../../Data"))
            {
                Directory.CreateDirectory("../../../Data");
            }

            var crm   = new CustomerResourceManager("../../../Data/customers.csv");
            var fleet = new Fleet("../../../Data/fleet.csv", "../../../Data/rentals.csv");

            var customerManager = new CustomerManager(crm, fleet);
            var fleetManager    = new FleetManager(fleet, crm);

            var mainMenu = new Menu("Main Menu", new Component[]
            {
                MenuGenerator.GenerateManager("Customers", customerManager).Menu,
                MenuGenerator.GenerateManager("Fleet", fleetManager).Menu
            });

            var manager = new MenuManager(mainMenu);

            var guac = new Guac(manager);

            guac.Focus(mainMenu);

            guac.KeyPressed += async(_, ev) =>
            {
                if (ev.Key.Key != ConsoleKey.Escape)
                {
                    return;
                }
                ev.Cancel = true;

                var exitResult = await guac.ShowDialogue(
                    "Exit", "Are you sure you want to exit?", new[]
                {
                    "Ok",
                    "Cancel"
                });

                if (exitResult == "Ok")
                {
                    ProgramRunning = false;
                    CleanUp(crm, fleet);
                    Environment.Exit(0);
                }
            };

            Console.CursorVisible = false;

            while (true)
            {
                guac.HandleEventLoop();

                if (!ProgramRunning)
                {
                    break;
                }
            }

            CleanUp(crm, fleet);

            // ReSharper disable once FunctionNeverReturns
        }
Exemple #49
0
        public static void SetTotalViewRange(this Fleet fleet, int value)
        {
            Type type = typeof(Fleet);

            type.GetProperty("TotalViewRange", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).SetValue(fleet, value);
        }
Exemple #50
0
        public string FleetFileImport(string FileName, string CallType)
        {
            int ValidRecords   = 0;
            int InValidRecords = 0;

            try
            {
                accessfileName = FileName + SiteConfigurationManager.GetAppSettingKey("FileImportExtension");
                fileName       = ClaimHelper.CompanyId + "_" + FileName;
                FileName       = fileName + SiteConfigurationManager.GetAppSettingKey("FileImportExtension");

                string logImport         = null;
                bool   FleetResult       = false;
                string rootFolderPath    = SiteConfigurationManager.GetAppSettingKey("TemplatePath") + "vehicleFile\\";
                string destinationPath   = rootFolderPath + "\\Archive\\";
                string fullPathToExcel   = rootFolderPath + accessfileName;
                string fullpathToArchive = destinationPath + accessfileName;

                LoggerDataAccess loggerDataAccess = new LoggerDataAccess();

                logImport           = loggerDataAccess.LogFileImport(FileName, "IMP_FL_INITIATED", ValidRecords.ToString(), InValidRecords.ToString(), null, null);
                ImportFileHistoryID = logImport;

                if (new FileInfo(fullpathToArchive).Exists == false)
                {
                    string    connString = string.Format("Provider =Microsoft.ACE.OLEDB.12.0;Data Source=" + fullPathToExcel + ";Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
                    DataTable dt         = FileManager.GetDataTable("SELECT * FROM [Sheet1$]", connString);

                    Thread.CurrentThread.CurrentCulture =
                        CultureInfo.CreateSpecificCulture("en-GB");
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");

                    var date = DateTime.Now;

                    if (CallType.ToLower() == "fleet")
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            Fleet Fleet = new Fleet()
                            {
                                CompanyAddressID = Convert.ToInt32(dt.Rows[i]["BranchID"].ToString()),
                                FleetID          = dt.Rows[i]["FleetID"].ToString(),
                                Make             = dt.Rows[i]["Make"].ToString(),
                                Model            = dt.Rows[i]["Model"].ToString(),
                                ModelYear        = Convert.ToInt32(dt.Rows[i]["ModelYear"].ToString()),
                                Colour           = dt.Rows[i]["Colour"].ToString(),
                                StartingMileage  = Convert.ToInt32(dt.Rows[i]["StartingMileage"].ToString()),
                                Payload          = dt.Rows[i]["Payload"].ToString(),
                                OwnerShipType    = dt.Rows[i]["OwnerShipType"].ToString(),
                                OverallLength    = dt.Rows[i]["OverallLength"].ToString(),
                                OverallWidth     = dt.Rows[i]["OverallWidth"].ToString(),
                                OverallHeight    = dt.Rows[i]["OverallHeight"].ToString(),
                                IsActive         = Convert.ToBoolean(dt.Rows[i]["IsActive"].ToString())
                            };
                            FleetResult = SaveFleet(Fleet, null, "");
                            if (FleetResult)
                            {
                                ValidRecords = ValidRecords + 1;
                            }
                            if (!FleetResult)
                            {
                                InValidRecords = InValidRecords + 1;
                            }
                        }
                    }
                    //Console.ReadLine();

                    string[] fileList = Directory.GetFiles(rootFolderPath, FileName);

                    if (Directory.Exists(rootFolderPath))
                    {
                        foreach (string file in fileList)
                        {
                            FileInfo mFile = new FileInfo(file);
                            if (new FileInfo(destinationPath + "\\" + mFile.Name).Exists == false)
                            {
                                mFile.MoveTo(destinationPath + "\\" + mFile.Name);
                            }
                        }
                    }
                }
                else if (new FileInfo(fullpathToArchive).Exists == true)
                {
                    return("File is already processed");
                }
                if (FleetResult)
                {
                    logImport = loggerDataAccess.LogFileImport(FileName, "IMP_FL_SCCS", ValidRecords.ToString(), InValidRecords.ToString(), null, ImportFileHistoryID);
                    return(FileName + ":- File imported successully.");
                }
                string eFileName;
                string errorFileName;

                LoggerDataAccess eloggerDataAccess = new LoggerDataAccess();

                eFileName     = "VehicleError_" + fileName + "_" + DateTime.Now.ToString("MMddyyyyHH");
                errorFileName = "VehicleFile\\error\\" + eFileName + ".error.txt";
                string filePath = SiteConfigurationManager.GetAppSettingKey("TemplatePath") + errorFileName;

                var v = FileManager.FileErrorLog(filePath, "Incorrect File Layout/FleetID already exists", "Error while processing file");

                logImport = loggerDataAccess.LogFileImport(FileName, "IMP_FL_FLD", ValidRecords.ToString(), InValidRecords.ToString(), errorFileName, ImportFileHistoryID);
                return(FileName + ":- File import Failed.");
            }
            catch (Exception ex)
            {
                string eFileName;
                string errorFileName;

                LoggerDataAccess eloggerDataAccess = new LoggerDataAccess();

                eFileName     = "VehicleError_" + fileName + "_" + DateTime.Now.ToString("MMddyyyyHH");
                errorFileName = "VehileFile\\error\\" + eFileName + ".error.txt";
                string filePath = SiteConfigurationManager.GetAppSettingKey("TemplatePath") + errorFileName;

                if (!string.IsNullOrEmpty(fileName))
                {
                    var v = FileManager.FileErrorLog(filePath, ex.Message, "Error with File");
                    eloggerDataAccess.LogFileImport(FileName, "IMP_FL_FLD", ValidRecords.ToString(), InValidRecords.ToString(), errorFileName, ImportFileHistoryID);
                }
                return(FileName + ":- File import Failed.");
            }
        }
        private static void Run(Options options)
        {
            var a = Fleet.TryLoad(options.PathA);

            if (a == null)
            {
                Console.WriteLine("**Failed to load fleet A**");
                return;
            }

            var b = Fleet.TryLoad(options.PathB);

            if (b == null)
            {
                Console.WriteLine("**Failed to load fleet B**");
                return;
            }

            var sim = new Simulation(a, Path.GetFileNameWithoutExtension(options.PathA), b, Path.GetFileNameWithoutExtension(options.PathB));

            Console.WriteLine("Created Scene");

            Report?report;

            using (var loga = File.CreateText("CaptainsLog_A.txt"))
                using (var logb = File.CreateText("CaptainsLog_B.txt"))
                {
                    sim.AddLog(0, loga);
                    sim.AddLog(1, logb);
                    report = sim.Run();
                }

            Console.WriteLine(report);

            var output = options.OutputPath ?? "output.json.deflate";

            using (var file = File.Create(output))
                using (var zip = new DeflateStream(file, CompressionLevel.Optimal))
                    using (var stream = new StreamWriter(zip))
                        using (var writer = new JsonTextWriter(stream)
                        {
                            Formatting = Formatting.None
                        })
                        {
                            report.Serialize(writer);
                            writer.Flush();
                            Console.WriteLine($"File Size (Compressed): {ToFileSize(file.Position)}");
                        }

            #if DEBUG
            using (var file = File.Create("output.json"))
                using (var stream = new StreamWriter(file))
                    using (var writer = new JsonTextWriter(stream)
                    {
                        Formatting = Formatting.Indented
                    })
                    {
                        report.Serialize(writer);
                        writer.Flush();
                        Console.WriteLine($"File Size (Uncompressed): {ToFileSize(file.Position)}");
                    }
            #endif
        }
Exemple #52
0
        public bool SaveFleet(Fleet Fleet, IList <Document> Documents, string CallType)
        {
            string documentXml       = string.Empty;
            string exceptionMessages = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(Fleet.FleetID))
                {
                    exceptionMessages = "FleetID is missing";
                }

                if (string.IsNullOrEmpty(Fleet.CompanyAddressID.ToString()))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "Branch ID is missing" : exceptionMessages + ", " + "Branch ID is missing";
                }

                if (string.IsNullOrEmpty(Fleet.Make))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "Make is missing" : exceptionMessages + ", " + "Make is missing";
                }
                if (string.IsNullOrEmpty(Fleet.Model))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "Model is missing" : exceptionMessages + ", " + "Model is missing";
                }
                if (string.IsNullOrEmpty(Fleet.ModelYear.ToString()))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "ModelYear is missing" : exceptionMessages + ", " + "ModelYear is missing";
                }
                if (string.IsNullOrEmpty(Fleet.Colour))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "Colour is missing" : exceptionMessages + ", " + "Colour is missing";
                }
                if (string.IsNullOrEmpty(Fleet.StartingMileage.ToString()))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "StartingMileage is missing" : exceptionMessages + ", " + "StartingMileage is missing";
                }
                if (string.IsNullOrEmpty(Fleet.Payload))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "Payload is missing" : exceptionMessages + ", " + "Payload is missing";
                }
                if (string.IsNullOrEmpty(Fleet.OwnerShipType))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "OwnerShipType is missing" : exceptionMessages + ", " + "OwnerShipType is missing";
                }
                if (string.IsNullOrEmpty(Fleet.OverallLength))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "OverallLength is missing" : exceptionMessages + ", " + "OverallLength is missing";
                }
                if (string.IsNullOrEmpty(Fleet.OverallWidth))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "OverallWidth is missing" : exceptionMessages + ", " + "OverallWidth is missing";
                }
                if (string.IsNullOrEmpty(Fleet.OverallHeight))
                {
                    exceptionMessages = string.IsNullOrEmpty(exceptionMessages) ? "OverallHeight is missing" : exceptionMessages + ", " + "OverallHeight is missing";
                }

                if (!string.IsNullOrEmpty(exceptionMessages))
                {
                    throw new Exception(exceptionMessages);
                }

                if (CallType == "Portal")
                {
                    if (Documents != null && Documents.Count > 0)
                    {
                        documentXml = Documents.ConvertToXmlWithoutNamespaces <Document>();
                    }
                    return(_userDataAccess.SaveFleet(Fleet, documentXml));
                }
                if (CallType != "Portal")
                {
                    if (Documents != null && Documents.Count > 0)
                    {
                        documentXml = Documents.ConvertToXmlWithoutNamespaces <Document>();
                    }
                    return(_userDataAccess.SaveFleet(Fleet, documentXml));
                }
                return(false);
            }
            catch (Exception ex)
            {
                string eFileName;
                string errorFileName;

                eFileName     = "VehicleError_" + fileName + "_" + DateTime.Now.ToString("MMddyyyyHH");
                errorFileName = "VehileFile\\error\\" + eFileName + ".error.txt";
                string filePath = SiteConfigurationManager.GetAppSettingKey("TemplatePath") + errorFileName;

                LoggerDataAccess eloggerDataAccess = new LoggerDataAccess();

                if (!string.IsNullOrEmpty(fileName))
                {
                    fileName = fileName + SiteConfigurationManager.GetAppSettingKey("FileImportExtension");
                    if (string.IsNullOrEmpty(Fleet.FleetID))
                    {
                        Fleet.FleetID = "Empty";
                    }

                    var v = FileManager.FileErrorLog(filePath, ex.Message, Fleet.FleetID);

                    eloggerDataAccess.LogFileImport(fileName, "IMP_FL_FLD", null, null, errorFileName, ImportFileHistoryID);
                }
                return(false);
            }
        }
Exemple #53
0
 private static Total CalcTotal(Fleet fleet)
 {
     return(fleet.Ships.Aggregate(new Total(), (sum, next) => sum.Add(next)));
 }
Exemple #54
0
        static void Main()
        {
            List <Customer> customers = new List <Customer>();
            List <Vehicle>  vehicles  = new List <Vehicle>();

            ////Create new economy class car
            //Vehicle.EconomyClass newEconomyCar = new Vehicle.EconomyClass("AAAA", Vehicle.EconomyClass.VehicleClass.Economy, "MAZDA", "ASX", 2000);
            ////Check economy car ToString function
            //WriteLine(newEconomyCar.ToString());
            ////Check economy car GetAttributesList function
            //newEconomyCar.GetAttributesList();

            ////Create new family class car
            //Vehicle.FamilyClass newFamilyCar = new Vehicle.FamilyClass("AAAB", Vehicle.FamilyClass.VehicleClass.Family, "KIA", "RIO", 2016);
            ////Check family car ToString function
            //WriteLine(newFamilyCar.ToString());
            ////Check family car GetAttibutesList function
            //newFamilyCar.GetAttributesList();


            ////Create new luxury class car
            //Vehicle.LuxuryClass newLuxuryCar = new Vehicle.LuxuryClass("AAAC", Vehicle.LuxuryClass.VehicleClass.Luxury, "KIA", "RIO", 2016);
            ////Check luxury car ToString function
            //WriteLine(newLuxuryCar.ToString());
            ////Check luxury car GetAttibutesList function
            //newLuxuryCar.GetAttributesList();


            ////Create new commercial class car
            //Vehicle.CommercialClass newCommercialCar = new Vehicle.CommercialClass("AAAD", Vehicle.CommercialClass.VehicleClass.Commercial,
            //"hitachi", "digger", 2006);
            ////Check commercial car ToString function
            //WriteLine(newCommercialCar.ToString());
            ////Check commercial car GetAttributesList function
            //newCommercialCar.GetAttributesList();
            ////Check commercial car SetVehicleClass function
            //newCommercialCar.SetVehicleClass();
            ////Check to see if SetVehicleClass function works.
            //newCommercialCar.GetAttributesList();
            //newCommercialCar.SetDailyRate();
            //newCommercialCar.GetAttributesList();

            ////Create new customer
            //Customer newCustomer = new Customer(1);
            ////Check customer ToString function
            //WriteLine(newCustomer.ToString());
            ////Check customer SetGender function
            //newCustomer.SetGender();
            ////Check to see if SetGender function works
            //WriteLine(newCustomer.ToString());



            Fleet newfleet = new Fleet();

            newfleet.ReturnCar("123HCB");



            ReadKey();
        }
Exemple #55
0
                private static string SpeedName(Fleet fleet)
                {
                    var speed = fleet.ActualShips.Min(s => (int?)s.Speed);

                    return(new[] { "", "低速", "高速", "高速+", "最速" }[(speed ?? 0) / 5]);
                }
Exemple #56
0
        private static void HandleAttack(object state)
        {
            if (celestials.Count == 0)
            {
                DateTime time     = ogamedService.GetServerTime();
                int      interval = Helpers.CalcRandomInterval(IntervalType.SomeSeconds);
                DateTime newTime  = time.AddMilliseconds(interval);
                defenderTimer.Change(interval, Timeout.Infinite);
                Helpers.WriteLog(LogType.Warning, LogSender.Defender, "Unable to handle attack at the moment: bot is still getting account info.");
                Helpers.WriteLog(LogType.Info, LogSender.Defender, "Next check at " + newTime.ToString());
                return;
            }
            foreach (AttackerFleet attack in attacks)
            {
                if ((bool)settings.TelegramMessenger.Active && (bool)settings.Defender.TelegramMessenger.Active)
                {
                    telegramMessenger.SendMessage("Player " + attack.AttackerName + " (" + attack.AttackerID + ") is attacking your planet " + attack.Destination.ToString() + " arriving at " + attack.ArrivalTime.ToString());
                }
                Celestial attackedCelestial = celestials.SingleOrDefault(planet => planet.Coordinate.Galaxy == attack.Destination.Galaxy && planet.Coordinate.System == attack.Destination.System && planet.Coordinate.Position == attack.Destination.Position && planet.Coordinate.Type == attack.Destination.Type);
                attackedCelestial = UpdatePlanet(attackedCelestial, UpdateType.Ships);
                Helpers.WriteLog(LogType.Warning, LogSender.Defender, "Player " + attack.AttackerName + " (" + attack.AttackerID + ") is attacking your planet " + attackedCelestial.ToString() + " arriving at " + attack.ArrivalTime.ToString());
                if (settings.Defender.SpyAttacker.Active)
                {
                    UpdateSlots();
                    if (slots.Free > 0)
                    {
                        if (attackedCelestial.Ships.EspionageProbe == 0)
                        {
                            Helpers.WriteLog(LogType.Warning, LogSender.Defender, "Could not spy attacker: no probes available.");
                        }
                        else
                        {
                            try
                            {
                                Coordinate destination = attack.Origin;
                                Ships      ships       = new Ships {
                                    EspionageProbe = (int)settings.Defender.SpyAttacker.Probes
                                };
                                int   fleetId = SendFleet(attackedCelestial, ships, destination, Missions.Spy, Speeds.HundredPercent);
                                Fleet fleet   = fleets.Single(fleet => fleet.ID == fleetId);
                                Helpers.WriteLog(LogType.Info, LogSender.Defender, "Spying attacker from " + attackedCelestial.ToString() + " to " + destination.ToString() + " with " + settings.Defender.SpyAttacker.Probes + " probes. Arrival at " + fleet.ArrivalTime.ToString());
                            }
                            catch (Exception e)
                            {
                                Helpers.WriteLog(LogType.Error, LogSender.Defender, "Could not spy attacker: an exception has occurred: " + e.Message);
                            }
                        }
                    }
                    else
                    {
                        Helpers.WriteLog(LogType.Warning, LogSender.Defender, "Could not send probes: no slots available.");
                    }
                }
                if (settings.Defender.MessageAttacker.Active)
                {
                    try
                    {
                        Random   random       = new Random();
                        string[] messages     = settings.Defender.MessageAttacker.Messages;
                        int      messageIndex = random.Next(0, messages.Length);
                        string   message      = messages[messageIndex];
                        ogamedService.SendMessage(attack.AttackerID, messages[messageIndex]);
                        Helpers.WriteLog(LogType.Info, LogSender.Defender, "Sent message \"" + message + "\" to attacker" + attack.AttackerName);
                    }
                    catch (Exception e)
                    {
                        Helpers.WriteLog(LogType.Error, LogSender.Defender, "Could not message attacker: an exception has occurred: " + e.Message);
                    }
                }
                if (settings.Defender.Autofleet.Active)
                {
                    UpdateSlots();
                    if (slots.Free > 0)
                    {
                        try
                        {
                            attackedCelestial = UpdatePlanet(attackedCelestial, UpdateType.Resources);
                            Celestial destination;
                            destination = celestials
                                          .Where(planet => planet.ID != attackedCelestial.ID)
                                          .Where(planet => planet.Coordinate.Type == (attackedCelestial.Coordinate.Type == Celestials.Moon ? Celestials.Planet : Celestials.Moon))
                                          .Where(planet => Helpers.CalcDistance(attackedCelestial.Coordinate, planet.Coordinate, serverData) == 5)
                                          .FirstOrDefault() ?? new Celestial {
                                ID = 0
                            };
                            if (destination.ID == 0)
                            {
                                destination = celestials
                                              .Where(planet => planet.ID != attackedCelestial.ID)
                                              .Where(planet => planet.Coordinate.Type == Celestials.Moon)
                                              .OrderBy(planet => Helpers.CalcDistance(attackedCelestial.Coordinate, planet.Coordinate, serverData))
                                              .FirstOrDefault() ?? new Celestial {
                                    ID = 0
                                };
                            }
                            if (destination.ID == 0)
                            {
                                destination = celestials
                                              .Where(planet => planet.ID != attackedCelestial.ID)
                                              .OrderBy(planet => Helpers.CalcDistance(attackedCelestial.Coordinate, planet.Coordinate, serverData))
                                              .FirstOrDefault() ?? new Celestial {
                                    ID = 0
                                };
                            }
                            if (destination.ID == 0)
                            {
                                Helpers.WriteLog(LogType.Warning, LogSender.Defender, "Could not fleetsave: no valid destination exists");
                                DateTime time     = ogamedService.GetServerTime();
                                int      interval = Helpers.CalcRandomInterval(IntervalType.AFewSeconds);
                                DateTime newTime  = time.AddMilliseconds(interval);
                                defenderTimer.Change(interval, Timeout.Infinite);
                                Helpers.WriteLog(LogType.Info, LogSender.Defender, "Next check at " + newTime.ToString());
                                return;
                            }

                            Ships ships = attackedCelestial.Ships;
                            ships.Crawler        = 0;
                            ships.SolarSatellite = 0;
                            if (ships.IsEmpty())
                            {
                                Helpers.WriteLog(LogType.Warning, LogSender.Defender, "Could not fleetsave: there is no fleet.");
                            }
                            else
                            {
                                Resources resources = Helpers.CalcMaxTransportableResources(ships, attackedCelestial.Resources, researches.HyperspaceTechnology, userInfo.Class);
                                int       fleetId   = SendFleet(attackedCelestial, ships, destination.Coordinate, Missions.Deploy, Speeds.TenPercent, resources, true);
                                if (fleetId != 0)
                                {
                                    Fleet fleet = fleets.Single(fleet => fleet.ID == fleetId);
                                    Helpers.WriteLog(LogType.Info, LogSender.Defender, "Fleetsaved to " + destination.ToString() + ". Arrival at " + fleet.ArrivalTime.ToString());
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Helpers.WriteLog(LogType.Error, LogSender.Defender, "Could not fleetsave: an exception has occurred: " + e.Message);
                            DateTime time     = ogamedService.GetServerTime();
                            int      interval = Helpers.CalcRandomInterval(IntervalType.AFewSeconds);
                            DateTime newTime  = time.AddMilliseconds(interval);
                            defenderTimer.Change(interval, Timeout.Infinite);
                            Helpers.WriteLog(LogType.Info, LogSender.Defender, "Next check at " + newTime.ToString());
                        }
                    }
                    else
                    {
                        Helpers.WriteLog(LogType.Warning, LogSender.Defender, "Could not fleetsave: no slots available.");
                        DateTime time     = ogamedService.GetServerTime();
                        int      interval = Helpers.CalcRandomInterval(IntervalType.AFewSeconds);
                        DateTime newTime  = time.AddMilliseconds(interval);
                        defenderTimer.Change(interval, Timeout.Infinite);
                        Helpers.WriteLog(LogType.Info, LogSender.Defender, "Next check at " + newTime.ToString());
                    }
                }
            }
        }
Exemple #57
0
        private void UpdateFleetState(Fleet fleet)
        {
            Action <int, string, string, Color> UpdateDisplay = (idx, name, state, color) =>
            {
                var cell = tableFleet.TableCells[idx - 1];
                cell.Header    = name;
                cell.Value     = state;
                cell.BackColor = color;
                cell.Visible   = state != null;

                tableFleet.RequestUpdate();
            };

            if (fleet == null)
            {
                UpdateDisplay(fleet.Id, "", null, Color.Transparent);
            }

            else
            {
                if (fleet.Expedition.Id > 0)
                {
                    var time      = fleet.Expedition.Remaining;
                    var remaining = time.HasValue
                                                ? $"{(int)time.Value.TotalHours:D2}:{time.Value.ToString(@"mm\:ss")}"
                                                : "--:--:--";
                    UpdateDisplay(fleet.Id, $"{fleet.Expedition.Id}번 원정", remaining, Color.FromArgb(0x20, 0x40, 0x80));
                }

                else if (fleet.IsInSortie)
                {
                    UpdateDisplay(fleet.Id, $"{fleet.Id}번 함대", "출격중", Color.FromArgb(0x7E, 0x01, 0x01));
                }

                else if (fleet.State.Situation == FleetSituation.Empty)
                {
                    UpdateDisplay(fleet.Id, $"{fleet.Id}번 함대", "없음", Color.FromArgb(0x3E, 0x3E, 0x42));
                }


                else if (fleet.State.HeavilyDamaged)
                {
                    UpdateDisplay(fleet.Id, $"{fleet.Id}번 함대", "대파 있음", Color.FromArgb(0xCF, 0x00, 0x00));
                }

                else if (fleet.State.Repairing)
                {
                    UpdateDisplay(fleet.Id, $"{fleet.Id}번 함대", "수리중", Color.FromArgb(0x5A, 0x40, 0x20));
                }

                else if (fleet.State.InShortSupply)
                {
                    UpdateDisplay(fleet.Id, $"{fleet.Id}번 함대", "보급 필요", Color.FromArgb(0x5A, 0x40, 0x20));
                }

                else if (fleet.State.FlagshipIsRepairShip)
                {
                    UpdateDisplay(fleet.Id, $"{fleet.Id}번 함대", "공작함 기함", Color.FromArgb(0x5A, 0x40, 0x20));
                }

                else if (fleet.State.Condition.IsRejuvenating)
                {
                    var time      = fleet.State.Condition.Remaining;
                    var remaining = time.HasValue
                                                ? $"{time.Value.ToString(@"mm\:ss")}"
                                                : "--:--";
                    UpdateDisplay(fleet.Id, $"{fleet.Id}번 함대", "회복중 " + remaining, Color.FromArgb(0x5A, 0x40, 0x20));
                }

                else
                {
                    UpdateDisplay(fleet.Id, $"{fleet.Id}번 함대", "출격 가능", Color.FromArgb(0x28, 0x64, 0x14));
                }
            }
        }
Exemple #58
0
        public void Sense()
        {
            var newFleets = Robot.Bodies
                .Where(b => b.Group?.Type == GroupTypes.Fleet) // check the sprite
                .GroupBy(b => b.Group)
                .Select(g => new Fleet
                {
                    ID = g.Key.ID,
                    Name = g.Key.Caption,
                    Sprite = g.Select(b => b.Sprite).FirstOrDefault(),
                    Color = g.Key.Color,
                    Ships = g.Select(b => new Ship
                    {
                        ID = b.ID,
                        Angle = b.Angle,
                        Momentum = b.Momentum,
                        Position = b.Position,
                        Size = b.Size
                    }).ToList()
                })
                .ToList();

            foreach (var fleet in AllVisibleFleets)
                fleet.PendingDestruction = true;
            foreach (var fleet in newFleets)
            {
                var existing = AllVisibleFleets.FirstOrDefault(f => f.ID == fleet.ID);
                if (existing != null)
                {
                    existing.Name = fleet.Name;
                    existing.Sprite = fleet.Sprite;
                    existing.Color = fleet.Color;
                    existing.PendingDestruction = false;

                    foreach (var ship in existing.Ships)
                        ship.PendingDestruction = true;

                    foreach (var ship in fleet.Ships)
                    {
                        var existingShip = existing.Ships.FirstOrDefault(s => s.ID == ship.ID);
                        if (existingShip != null)
                        {
                            existingShip.Position = ship.Position;
                            existingShip.Momentum = ship.Momentum;
                            existingShip.Size = ship.Size;
                            existingShip.Angle = ship.Angle;
                            ship.PendingDestruction = false;
                        }
                        else
                            existing.Ships.Add(ship);

                        existing.Ships = existing.Ships.Where(s => !s.PendingDestruction).ToList();
                    }
                }
                else
                    AllVisibleFleets.Add(fleet);
            }
            AllVisibleFleets = AllVisibleFleets.Where(f => !f.PendingDestruction).ToList();

            MyFleet = AllVisibleFleets.FirstOrDefault(f => f.ID == Robot.FleetID);
        }
Exemple #59
0
 public static double CalcViewRange(this Fleet fleet)
 {
     return(ViewRangeCalcLogic.Get(KanColleClient.Current.Settings.ViewRangeCalcType).Calc(fleet.Ships));
 }
Exemple #60
0
        protected override double CalculateCore(Fleet rpFleet)
        {
            var rShipLoS            = .0;
            var rEquipmentLoS       = .0;
            var rEmptyShipSlotBonus = 12;

            foreach (var rShip in rpFleet.Ships)
            {
                if ((rShip.State & ShipState.Evacuated) != 0)
                {
                    continue;
                }

                rEmptyShipSlotBonus -= 2;

                var rShipLoSBase = rShip.Status.LoS;

                foreach (var rSlot in rShip.Slots)
                {
                    if (!rSlot.HasEquipment)
                    {
                        continue;
                    }

                    var rInfo = rSlot.Equipment.Info;
                    var rLoS  = (double)rInfo.LoS;

                    rShipLoSBase -= rInfo.LoS;

                    var rLevel = rSlot.Equipment.Level;
                    if (rLevel > 0)
                    {
                        switch (rInfo.Type)
                        {
                        case EquipmentType.ReconSeaplane:
                            rLoS += Math.Sqrt(rLevel) * 1.2;
                            break;

                        case EquipmentType.SmallRadar:
                            rLoS += Math.Sqrt(rLevel) * 1.25;
                            break;

                        case EquipmentType.LargeRadar:
                            rLoS += Math.Sqrt(rLevel) * 1.4;
                            break;
                        }
                    }

                    switch (rInfo.Type)
                    {
                    case EquipmentType.CarrierBasedTorpedoBomber:
                    case EquipmentType.JetPoweredAttackAircraft:
                        rEquipmentLoS += rLoS * .8;
                        break;

                    case EquipmentType.CarrierBasedRecon:
                    case EquipmentType.JetPoweredRecon:
                        rEquipmentLoS += rLoS;
                        break;

                    case EquipmentType.ReconSeaplane:
                        rEquipmentLoS += rLoS * 1.2;
                        break;

                    case EquipmentType.SeaplaneBomber:
                        rEquipmentLoS += rLoS * 1.1;
                        break;

                    case EquipmentType.SmallRadar:
                        rEquipmentLoS += rLoS * .6;
                        break;

                    case EquipmentType.LargeRadar:
                        rEquipmentLoS += rLoS * .6;
                        break;

                    default:
                        rEquipmentLoS += rLoS * .6;
                        break;
                    }
                }

                rShipLoS += Math.Sqrt(rShipLoSBase);
            }

            var rAdmiralLoS = Math.Ceiling(rpFleet.Port.Admiral.Level * .4);

            return(rShipLoS + rEquipmentLoS * r_NodeFactor - rAdmiralLoS + rEmptyShipSlotBonus);
        }