void UpdateFleets(IEnumerable <Fleet> rpFleets) { Fleets = KanColleGame.Current.Port.Fleets.Table.Values.Select(r => new FleetViewModel(r)).ToList(); SelectedFleet = Fleets.FirstOrDefault(); r_Parent.Overview.Fleets = Fleets; }
public StatusResult GetStatus(StatusRequest request) { var status = new StatusResult() { Success = true, Status = this.Status, IsGameOver = this.GameOver, Waiting = this.Waiting, CurrentTurn = Turn, NextTurnStart = endServerTurn, EndOfCurrentTurn = endPlayerTurn, PlayerTurnLength = (int)PLAYER_TURN_LENGTH, ServerTurnLength = (int)SERVER_TURN_LENGTH, Planets = Planets.Select(p => Mapper.Map <Shared.Planet>(p)).ToList(), Fleets = Fleets.Select(f => Mapper.Map <Shared.Fleet>(f)).ToList(), PlayerA = 1, PlayerAScore = _getPlayerScore(1), PlayerAScoreOverTime = PlayerAScoreOverTime, PlayerB = 2, PlayerBScore = _getPlayerScore(2), PlayerBScoreOverTime = PlayerBScoreOverTime }; return(status); }
private void PortHandler(port_port api) { System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); Staff.Current.Admiral.BasicHandler(api.api_basic); ConditionHelper.Instance.BeginUpdate(); Staff.Current.Shipyard.RepairDocks.ForEach(x => x.Ship?.IgnoreNextCondition()); if (Ships == null) { Ships = new IDTable <int, Ship>(api.api_ship.Select(x => new Ship(x))); } else { Ships.UpdateAll(api.api_ship, x => x.api_id); } ConditionHelper.Instance.EndUpdate(); Staff.Current.Admiral.ShipCount = api.api_ship.Length; Staff.Current.Shipyard.NDockHandler(api.api_ndock); DecksHandler(api.api_deck_port); if (Fleets.Any(x => x.MissionState == Fleet.FleetMissionState.Complete)) { Logger.Loggers.MaterialLogger.ForceLog = false; } Material.MaterialHandler(api.api_material); CombinedFleet = (CombinedFleetType)api.api_combined_flag; Fleets.ForEach(x => x.CheckHomeportRepairingTime(false)); }
/// <summary> /// Attempts to create the specified fleets on Car Delivery Network. /// </summary> /// <param name="fleets">The collection of fleets to create.</param> /// <returns>A collection of the successfully created fleets.</returns> public Users CreateFleets(Fleets fleets) { if (fleets == null || fleets.Count == 0) { throw new ArgumentException("Fleets collection was null or empty"); } return(Users.FromString(CallWithRetry("Fleets", "POST", false, fleets), _interfaceFormat)); }
private void checkSprite() { //if in a fleet, hide sprite if (assignedFleet = null) { shipSr.sprite = shipSprite; } else { shipSr.sprite = null; } }
public void VerifySubGroups() { foreach (Fleet f in Fleets) { if (f.Orbiting != this) { Fleets.Remove(f); } } }
internal void UpdatePort(RawPort rpPort) { UpdateAdmiral(rpPort.Basic); Materials.Update(rpPort.Materials); UpdateShips(rpPort); UpdateRepairDocks(rpPort.RepairDocks); Fleets.Update(rpPort); }
/// <summary> /// 更新直前の艦船データをコピーして退避します。 /// </summary> public void EvacuatePreviousShips() { if (Fleets.Values.Any(f => f != null && f.IsInSortie)) { return; } PreviousShips = new IDDictionary <ShipData>(KCDatabase.Instance.Ships.Values); IsAnchorageRepaired = Fleets.ToDictionary(f => f.Key, f => f.Value.CanAnchorageRepair); PreviousDockingID = new HashSet <int>(KCDatabase.Instance.Docks.Values.Select(d => d.ShipID)); }
protected override void GenMoves() { // if I have no planets left, do nothing var myPlanets = MyPlanets(); if (myPlanets.Count == 0) { return; } // find my strongest planet var strongest = myPlanets.OrderBy(p => p.population_).Last(); // find my fleet destinations var dests = Fleets.Select(f => f.dst_); // Get enemy planets not under attack any of my fleets var enemyPlanets = EnemyPlanets().Where(p => !dests.Contains(p.id_)); if (enemyPlanets.Count() > 0) { // find weakest (not under attack by me) and attack if possible var weakest = enemyPlanets.OrderBy(p => p.population_).First(); var dist = Distance(weakest, strongest); int needed = weakest.population_ + (dist + 1) * weakest.growthRate_ + 1; if (strongest.population_ >= needed) { // we can kill it - do so. LaunchFleet(strongest.id_, weakest.id_, needed); } } if (Commands.Count == 0) { // no command yet, kill any neutral planet (not under attack already) if possible var neutral = NeutralPlanets().Where(p => !dests.Contains(p.id_)); if (neutral.Count() > 0) { var weakest = neutral.OrderBy(p => p.population_).First(); if (strongest.population_ > weakest.population_) { // we can kill it - do so. LaunchFleet(strongest.id_, weakest.id_, weakest.population_ + 1); } } } if ((Commands.Count == 0) && (myPlanets.Count > 1)) { // no command yet, use second strongest planet to feed strongest planet var second = myPlanets.OrderByDescending(p => p.population_).Skip(1).First(); LaunchFleet(second.id_, strongest.id_, second.population_ / 2); } }
private void DecksHandler(getmember_deck[] api) { if (Fleets == null) { Fleets = new IDTable <int, Fleet>(api.Select(x => new Fleet(x))).WithSyncBindingEnabled(); SelectedFleet = 0; } else { Fleets.UpdateAll(api, x => x.api_id); } }
private void ReportBattleWon() { foreach (IFleet fleet in DisabledFleets) { fleet.LeaveField(this); } IFleet winner = Fleets.Where(x => x.WorkingStarShips.Count > 0).FirstOrDefault(); BattleResults.Messages.Add("The battle has been won and only the " + winner.Name + " fleet survives!"); BattleResults.Messages.Add("The " + winner.Name + " fleet still has " + Fleets.Where(x => x.WorkingStarShips.Count > 0).FirstOrDefault().WorkingStarShips.Count + " ship's left!"); }
void changeSelection(Fleets fleet) { if(selectedFleets.Contains(fleet)){ selectedFleets.Remove(fleet); fleet.SetGlow = false; Debug.Log ("Unselected fleet: " + fleet.fleetName); } else{ selectedFleets.Add(fleet); fleet.SetGlow = true; Debug.Log ("Selected fleet: " + fleet.fleetName); } }
void NewGame() { if (timerGame != null) { timerGame.Stop(); } if (timerTime != null) { timerTime.Stop(); } RemoveGameElements(); gameData = new GameData(); gameData.FleetPercent = 50; galaxy = new Galaxy(CanvasGame); galaxy.MouseLeftButtonDown = silverlightControlPlanet_MouseLeftButtonDown; galaxy.MouseRightButtonDown = silverlightControlPlanet_MouseRightButtonDown; galaxy.Generate(); // Hard level: more enemy planets if (GameDifficulty == Difficulty.Hard) { galaxy.AddEnemyPlanets(GameParameters.HARD_LEVEL_PLANET_NUM); } // Ez a SetEdges ele kell! currentPlanet = galaxy.GetFirstPlanet(); CreateEdges(); SetEdges(currentPlanet); fleets = new Fleets(); SetFrame(currentPlanet); SetRadius(currentPlanet); SetFace(currentPlanet); silverlightControlInfoPanel.DataContext = currentPlanet; silverlightControlGameInfo.DataContext = gameData; gameTime = new DateTime(2011, 01, 01, 0, 0, 0); TextBlockTime.Text = gameTime.ToString("HH:mm:ss"); silverlightControlFrame.Visibility = Visibility.Visible; }
public override void LoadFromResponse(string apiname, dynamic data) { switch (apiname) { case "api_req_combined_battle/goback_port": foreach (int index in KCDatabase.Instance.Battle.Result.EscapingShipIndex) { Fleets[(index - 1) < 6 ? 1 : 2].Escape((index - 1) % 6); } break; case "api_get_member/ndock": foreach (var fleet in Fleets.Values) { fleet.LoadFromResponse(apiname, data); } break; default: base.LoadFromResponse(apiname, (object)data); //api_port/port, api_get_member/deck foreach (var elem in data) { int id = (int)elem.api_id; if (!Fleets.ContainsKey(id)) { var a = new FleetData(); a.LoadFromResponse(apiname, elem); Fleets.Add(a); } else { Fleets[id].LoadFromResponse(apiname, elem); } } break; } //泊地修理関連 if (apiname == "api_port/port") { if ((DateTime.Now - AnchorageRepairingTimer).TotalMinutes >= 20 || AnchorageRepairingTimer == DateTime.MinValue) { ResetAnchorageRepairing(); } } }
public void Save(string directory) { Directory.CreateDirectory(directory); Bodies.SerializeXml(directory + "bodies.xml"); Planets.SerializeXml(directory + "planets.xml"); Governments.SerializeXml(directory + "governments.xml"); Characters.SerializeXml(directory + "characters.xml"); Fleets.SerializeXml(directory + "fleets.xml"); Map.SerializeXml(directory + "map.xml"); Militaries.SerializeXml(directory + "militaries.xml"); new Serializer <Date>().Serialize(directory + "date.xml", Date); new Serializer <Player>().Serialize(directory + "player.xml", Player); }
// Issue an order. This function takes num_ships off the source_planet, // puts them into a newly-created fleet, calculates the distance to the // destination_planet, and sets the fleet's total trip time to that // distance. Checks that the given player_id is allowed to give the given // order. If not, the offending player is kicked from the game. If the // order was carried out without any issue, and everything is peachy, then // 0 is returned. Otherwise, -1 is returned. public int IssueOrder(int playerID, int sourcePlanet, int destinationPlanet, int numShips) { Planet source = Planets[sourcePlanet]; bool isIllegalMove = source.Owner != playerID || numShips > source.NumShips || numShips < 0; if (isIllegalMove) { string message = String.Format( "Illegal move player: {0}. From planet {1} owned by {2} with {3} ships, wants to send {4} ships", playerID, sourcePlanet, source.Owner, numShips, source.NumShips); System.Diagnostics.Debug.Assert(false, message); WriteLogMessage(message); DropPlayer(playerID); return(-1); } source.RemoveShips(numShips); string fleetKey = playerID + ";" + sourcePlanet + ";" + destinationPlanet; Fleet duplicate; if (deDupe.TryGetValue(fleetKey, out duplicate)) { //ha there is no add... duplicate.RemoveShips(-numShips); } else { int distance = Distance(sourcePlanet, destinationPlanet); Fleet f = new Fleet(source.Owner, numShips, sourcePlanet, destinationPlanet, distance, distance); deDupe.Add(fleetKey, f); Fleets.Add(f); } return(0); }
private void ChargeHandler(hokyu_charge api) { foreach (var s in api.api_ship) { var ship = Ships[s.api_id]; ship.Fuel = new LimitedValue(s.api_fuel, ship.Fuel.Max); ship.Bull = new LimitedValue(s.api_bull, ship.Bull.Max); for (int i = 0; i < ship.Slots.Count; i++) { ship.Slots[i].AirCraft = new LimitedValue(s.api_onslot[i], ship.Slots[i].AirCraft.Max); } ship.UpdateStatus(); } Material.Fuel = api.api_material[0]; Material.Bull = api.api_material[1]; Material.Steel = api.api_material[2]; Material.Bauxite = api.api_material[3]; Fleets.ForEach(x => x.UpdateStatus()); }
public NavalBase(IGameProvider listener, ILocalizationService localization) { Localization = localization; MasterData = new MasterDataRoot(listener, localization); Quests = new QuestManager(listener, localization); _allEquipment = new IdTable<EquipmentId, Equipment, IRawEquipment, NavalBase>(this); _buildingDocks = new IdTable<BuildingDockId, BuildingDock, IRawBuildingDock, NavalBase>(this); _repairingDocks = new IdTable<RepairingDockId, RepairingDock, IRawRepairingDock, NavalBase>(this); _useItems = new IdTable<UseItemId, UseItemCount, IRawUseItemCount, NavalBase>(this); _allShips = new IdTable<ShipId, Ship, IRawShip, NavalBase>(this); _fleets = new IdTable<FleetId, Fleet, IRawFleet, NavalBase>(this); _maps = new IdTable<MapId, Map, IRawMap, NavalBase>(this); _airForce = new IdTable<(MapAreaId MapArea, AirForceGroupId GroupId), AirForceGroup, IRawAirForceGroup, NavalBase>(this); listener.AllEquipmentUpdated += (t, msg) => _allEquipment.BatchUpdate(msg, t); listener.BuildingDockUpdated += (t, msg) => _buildingDocks.BatchUpdate(msg, t); listener.UseItemUpdated += (t, msg) => _useItems.BatchUpdate(msg, t); listener.AdmiralUpdated += (t, msg) => { if (Admiral?.Id != msg.Id) { var @new = new Admiral(msg, this, t); AdmiralChanging?.Invoke(t, Admiral, @new); Admiral = @new; NotifyPropertyChanged(nameof(Admiral)); } else Admiral.Update(msg, t); }; listener.MaterialsUpdated += (t, msg) => { var materials = Materials; msg.Apply(ref materials); if (Materials != materials) { Materials = materials; MaterialsUpdating?.Invoke(t, Materials, materials, msg.Reason); } }; listener.HomeportReturned += (t, msg) => _allShips.BatchUpdate(msg.Ships, t); listener.CompositionChanged += (t, msg) => { var fleet = Fleets[msg.FleetId]; if (msg.ShipId is ShipId shipId) { var ship = AllShips[shipId]; fleet.ChangeComposition(msg.Index, ship, Fleets.FirstOrDefault(x => x.Ships.Contains(ship))); } else fleet.ChangeComposition(msg.Index, null, null); }; listener.FleetsUpdated += (t, msg) => _fleets.BatchUpdate(msg, t); listener.FleetPresetSelected += (t, msg) => Fleets[msg.Id].Update(msg, t); listener.ShipEquipmentUdated += (t, msg) => AllShips[msg.ShipId].UpdateEquipments(msg.EquipmentIds); listener.ShipExtraSlotOpened += (t, msg) => AllShips[msg].ExtraSlot = new Slot(); listener.PartialFleetsUpdated += (t, msg) => _fleets.BatchUpdate(msg, t, removal: false); listener.PartialShipsUpdated += (t, msg) => _allShips.BatchUpdate(msg, t, removal: false); listener.RepairingDockUpdated += (t, msg) => _repairingDocks.BatchUpdate(msg, t); listener.ShipSupplied += (t, msg) => { foreach (var raw in msg) AllShips[raw.ShipId]?.Supply(raw); }; listener.RepairStarted += (t, msg) => { if (msg.InstantRepair) AllShips[msg.ShipId]?.SetRepaired(); }; listener.InstantRepaired += (t, msg) => { var dock = RepairingDocks[msg]; dock.State = RepairingDockState.Empty; dock.RepairingShip = null; }; listener.InstantBuilt += (t, msg) => BuildingDocks[msg].State = BuildingDockState.BuildCompleted; listener.ShipBuildCompleted += (t, msg) => { _allEquipment.BatchUpdate(msg.Equipments, t, removal: false); _allShips.Add(msg.Ship, t); }; listener.EquipmentCreated += (t, msg) => { if (msg.IsSuccess) _allEquipment.Add(msg.Equipment, t); }; listener.ShipDismantled += (t, msg) => ShipDismantling?.Invoke(t, RemoveShips(msg.ShipIds, msg.DismantleEquipments, t), msg.DismantleEquipments); listener.EquipmentDismantled += (t, msg) => EquipmentDismantling?.Invoke(t, RemoveEquipments(msg, t)); listener.EquipmentImproved += (t, msg) => { var consumed = RemoveEquipments(msg.ConsumedEquipmentIds, t); var original = AllEquipment[msg.EquipmentId]; EquipmentImproving?.Invoke(t, original, msg.UpdatedTo, consumed, msg.IsSuccess); if (msg.IsSuccess) original.Update(msg.UpdatedTo, t); }; listener.ShipPoweruped += (t, msg) => { var consumed = RemoveShips(msg.ConsumedShipIds, true, t); var original = AllShips[msg.ShipId]; ShipPoweruping?.Invoke(t, original, msg.UpdatedTo, consumed); original.Update(msg.UpdatedTo, t); }; listener.MapsUpdated += (t, msg) => _maps.BatchUpdate(msg, t); listener.AirForceUpdated += (t, msg) => _airForce.BatchUpdate(msg, t); listener.AirForcePlaneSet += (t, msg) => { var group = AirForce[(msg.MapAreaId, msg.GroupId)]; group.Distance = msg.NewDistance; group.squadrons.BatchUpdate(msg.UpdatedSquadrons, t, removal: false); };
/// <summary> /// Attempts to create the specified fleets on Car Delivery Network. /// </summary> /// <param name="fleets">The collection of fleets to create.</param> /// <returns>A collection of the successfully created fleets.</returns> public Users CreateFleets(Fleets fleets) { if (fleets == null || fleets.Count == 0) throw new ArgumentException("Fleets collection was null or empty"); return Users.FromString(CallWithRetry("Fleets", "POST", false, fleets), _interfaceFormat); }
private void Ship3Handler(getmember_ship_deck api) { Ships.UpdateWithoutRemove(api.api_ship_data, x => x.api_id); Fleets.UpdateWithoutRemove(api.api_deck_data, x => x.api_id); }
internal Port() { ApiService.Subscribe("api_get_member/ship2", r => { UpdateShips(r.Json["api_data"].ToObject <RawShip[]>()); Fleets.Update(r.Json["api_data_deck"].ToObject <RawFleet[]>()); }); ApiService.Subscribe("api_get_member/ship_deck", r => { var rData = r.GetData <RawShipsAndFleets>(); foreach (var rRawShip in rData.Ships) { Ships[rRawShip.ID].Update(rRawShip); } var rRawFleet = rData.Fleets[0]; Fleets[rRawFleet.ID].Update(rRawFleet); OnPropertyChanged(nameof(Ships)); }); ApiService.Subscribe("api_get_member/ship3", r => { var rData = r.GetData <RawShipsAndFleets>(); foreach (var rShip in rData.Ships) { Ships[rShip.ID].Update(rShip); } Fleets.Update(rData.Fleets); ProcessUnequippedEquipment(r.Json["api_data"]["api_slot_data"]); }); ApiService.Subscribe("api_get_member/unsetslot", r => ProcessUnequippedEquipment(r.Json["api_data"])); ApiService.Subscribe("api_get_member/require_info", r => ProcessUnequippedEquipment(r.Json["api_data"]["api_unsetslot"])); ApiService.Subscribe("api_req_kaisou/slot_exchange_index", r => { Ship rShip; if (Ships.TryGetValue(int.Parse(r.Parameters["api_id"]), out rShip)) { rShip.UpdateEquipmentIDs(r.GetData <RawEquipmentIDs>().EquipmentIDs); rShip.OwnerFleet?.Update(); } }); ApiService.Subscribe("api_req_kaisou/open_exslot", r => { Ship rShip; if (Ships.TryGetValue(int.Parse(r.Parameters["api_id"]), out rShip)) { rShip.InstallReinforcementExpansion(); } }); ApiService.Subscribe("api_req_kaisou/slot_deprive", r => { var rData = r.GetData <RawEquipmentRelocationResult>(); var rDestionationShip = Ships[rData.Ships.Destination.ID]; var rOriginShip = Ships[rData.Ships.Origin.ID]; rDestionationShip.Update(rData.Ships.Destination); rOriginShip.Update(rData.Ships.Origin); rDestionationShip.OwnerFleet?.Update(); rOriginShip.OwnerFleet?.Update(); if (rData.UnequippedEquipment != null) { UnequippedEquipment[(EquipmentType)rData.UnequippedEquipment.Type] = rData.UnequippedEquipment.IDs.Select(rpID => Equipment[rpID]).ToArray(); } }); ApiService.Subscribe("api_req_kaisou/powerup", r => { var rShipID = int.Parse(r.Parameters["api_id"]); var rData = r.GetData <RawModernizationResult>(); var rConsumedShips = r.Parameters["api_id_items"].Split(',').Select(rpID => Ships[int.Parse(rpID)]).ToArray(); var rConsumedEquipment = rConsumedShips.SelectMany(rpShip => rpShip.EquipedEquipment).ToArray(); foreach (var rEquipment in rConsumedEquipment) { Equipment.Remove(rEquipment); } foreach (var rShip in rConsumedShips) { Ships.Remove(rShip); } RemoveEquipmentFromUnequippedList(rConsumedEquipment); UpdateShipsCore(); OnPropertyChanged(nameof(Equipment)); Fleets.Update(rData.Fleets); Ship rModernizedShip; if (Ships.TryGetValue(rShipID, out rModernizedShip)) { if (!rData.Success) { Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_Modernization_Failure, rModernizedShip.Info.TranslatedName)); } else { var rOriginal = rModernizedShip.RawData; var rNow = rData.Ship; var rInfo = rModernizedShip.Info; var rFirepowerDiff = rNow.ModernizedStatus[0] - rOriginal.ModernizedStatus[0]; var rTorpedoDiff = rNow.ModernizedStatus[1] - rOriginal.ModernizedStatus[1]; var rAADiff = rNow.ModernizedStatus[2] - rOriginal.ModernizedStatus[2]; var rArmorDiff = rNow.ModernizedStatus[3] - rOriginal.ModernizedStatus[3]; var rLuckDiff = rNow.Luck[0] - rOriginal.Luck[0]; var rFirepowerRemain = rInfo.FirepowerMaximum - rInfo.FirepowerMinimum - rNow.ModernizedStatus[0]; var rTorpedoRemain = rInfo.TorpedoMaximum - rInfo.TorpedoMinimum - rNow.ModernizedStatus[1]; var rAARemain = rInfo.AAMaximum - rInfo.AAMinimum - rNow.ModernizedStatus[2]; var rArmorRemain = rInfo.ArmorMaximum - rInfo.ArmorMinimum - rNow.ModernizedStatus[3]; var rLuckRemain = rNow.Luck[1] - rNow.Luck[0]; var rMaximumStatuses = new List <string>(5); var rNotMaximumStatuses = new List <string>(5); var rUseText = !Preference.Instance.UI.UseGameIconsInModernizationMessage.Value; var rShowStatusGrowth = Preference.Instance.UI.ShowStatusGrowthInModernizationMessage.Value; if (rFirepowerDiff > 0) { var rHeader = rUseText ? StringResources.Instance.Main.Ship_ToolTip_Status_Firepower : "[icon]firepower[/icon]"; if (rFirepowerRemain > 0) { rNotMaximumStatuses.Add(rShowStatusGrowth ? $"{rHeader} +{rFirepowerDiff}" : $"{rHeader} {rFirepowerRemain}"); } else { rMaximumStatuses.Add(rHeader + " MAX"); } } if (rTorpedoDiff > 0) { var rHeader = rUseText ? StringResources.Instance.Main.Ship_ToolTip_Status_Torpedo : "[icon]torpedo[/icon]"; if (rTorpedoRemain > 0) { rNotMaximumStatuses.Add(rShowStatusGrowth ? $"{rHeader} +{rTorpedoDiff}" : $"{rHeader} {rTorpedoRemain}"); } else { rMaximumStatuses.Add(rHeader + " MAX"); } } if (rAADiff > 0) { var rHeader = rUseText ? StringResources.Instance.Main.Ship_ToolTip_Status_AA : "[icon]aa[/icon]"; if (rAARemain > 0) { rNotMaximumStatuses.Add(rShowStatusGrowth ? $"{rHeader} +{rAADiff}" : $"{rHeader} {rAARemain}"); } else { rMaximumStatuses.Add(rHeader + " MAX"); } } if (rArmorDiff > 0) { var rHeader = rUseText ? StringResources.Instance.Main.Ship_ToolTip_Status_Armor : "[icon]armor[/icon]"; if (rArmorRemain > 0) { rNotMaximumStatuses.Add(rShowStatusGrowth ? $"{rHeader} +{rArmorDiff}" : $"{rHeader} {rArmorRemain}"); } else { rMaximumStatuses.Add(rHeader + " MAX"); } } if (rLuckDiff > 0) { var rHeader = rUseText ? StringResources.Instance.Main.Ship_ToolTip_Status_Luck : "[icon]luck[/icon]"; if (rLuckRemain > 0) { rNotMaximumStatuses.Add(rShowStatusGrowth ? $"{rHeader} +{rLuckDiff}" : $"{rHeader} {rLuckRemain}"); } else { rMaximumStatuses.Add(rHeader + " MAX"); } } var rBuilder = new StringBuilder(128); rBuilder.AppendFormat(StringResources.Instance.Main.Log_Modernization_Success, rModernizedShip.Info.TranslatedName); rBuilder.Append(" ("); var rSeparator = !Preference.Instance.UI.UseGameIconsInModernizationMessage.Value ? StringResources.Instance.Main.Log_Modernization_Separator_Type1 : " "; if (rMaximumStatuses.Count > 0) { rBuilder.Append(rMaximumStatuses.Join(rSeparator)); } if (rMaximumStatuses.Count > 0 && rNotMaximumStatuses.Count > 0) { rBuilder.Append(StringResources.Instance.Main.Log_Modernization_Separator_Type2); } if (rNotMaximumStatuses.Count > 0) { if (!rShowStatusGrowth) { rBuilder.Append(StringResources.Instance.Main.Log_Modernization_Remainder); } rBuilder.Append(rNotMaximumStatuses.Join(rSeparator)); } rBuilder.Append(')'); Logger.Write(LoggingLevel.Info, rBuilder.ToString()); } rModernizedShip.Update(rData.Ship); } }); ApiService.Subscribe("api_req_kousyou/createship", r => ConstructionDocks[int.Parse(r.Parameters["api_kdock_id"])].IsConstructionStarted = true); ApiService.Subscribe("api_req_kousyou/getship", r => { var rData = r.GetData <RawConstructionResult>(); UpdateConstructionDocks(rData.ConstructionDocks); AddEquipment(rData.Equipment); Ships.Add(new Ship(rData.Ship)); UpdateShipsCore(); }); ApiService.Subscribe("api_req_kousyou/createship_speedchange", r => { if (r.Parameters["api_highspeed"] == "1") { var rDock = ConstructionDocks[int.Parse(r.Parameters["api_kdock_id"])]; if (!rDock.IsLargeShipConstruction.GetValueOrDefault()) { Materials.InstantConstruction--; } else { Materials.InstantConstruction -= 10; } rDock.CompleteConstruction(); } }); ApiService.Subscribe("api_req_kousyou/createitem", r => { var rData = r.GetData <RawEquipmentDevelopment>(); if (!rData.Success) { return; } UnequippedEquipment[(EquipmentType)rData.EquipmentType] = r.Json["api_data"]["api_unsetslot"].Select(rpID => Equipment[(int)rpID]).ToArray(); }); ApiService.Subscribe("api_req_kousyou/destroyship", r => { Materials.Update(r.Json["api_data"]["api_material"].ToObject <int[]>()); var rShip = Ships[int.Parse(r.Parameters["api_ship_id"])]; foreach (var rEquipment in rShip.EquipedEquipment) { Equipment.Remove(rEquipment); } OnPropertyChanged(nameof(Equipment)); RemoveEquipmentFromUnequippedList(rShip.EquipedEquipment); rShip.OwnerFleet?.Remove(rShip); Ships.Remove(rShip); UpdateShipsCore(); }); ApiService.Subscribe("api_req_kousyou/destroyitem2", r => { var rEquipmentIDs = r.Parameters["api_slotitem_ids"].Split(',').Select(int.Parse); foreach (var rEquipmentID in rEquipmentIDs) { Equipment.Remove(rEquipmentID); } OnPropertyChanged(nameof(Equipment)); var rMaterials = r.Json["api_data"]["api_get_material"].ToObject <int[]>(); Materials.Fuel += rMaterials[0]; Materials.Bullet += rMaterials[1]; Materials.Steel += rMaterials[2]; Materials.Bauxite += rMaterials[3]; }); ApiService.Subscribe("api_req_kousyou/remodel_slotlist_detail", r => { var rID = r.Parameters["api_slot_id"]; var rEquipment = Equipment[int.Parse(rID)]; Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_EquipmentImprovement_Ready, rEquipment.Info.TranslatedName, rEquipment.LevelText, rID)); }); ApiService.Subscribe("api_req_kousyou/remodel_slot", r => { var rData = (RawImprovementResult)r.Data; var rEquipment = Equipment[int.Parse(r.Parameters["api_slot_id"])]; Materials.Update(rData.Materials); if (!rData.Success) { Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_EquipmentImprovement_Failure, rEquipment.Info.TranslatedName, rEquipment.LevelText)); } else { var rUpgraded = rEquipment.Info.ID != rData.ImprovedEquipment.EquipmentID; rEquipment.Update(rData.ImprovedEquipment); if (!rUpgraded) { Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_EquipmentImprovement_Success, rEquipment.Info.TranslatedName, rEquipment.LevelText)); } else { Logger.Write(LoggingLevel.Info, string.Format(StringResources.Instance.Main.Log_EquipmentImprovement_Upgrade, rEquipment.Info.TranslatedName, rEquipment.LevelText)); } } if (rData.ConsumedEquipmentID != null) { var rConsumedEquipment = rData.ConsumedEquipmentID.Select(rpID => Equipment[rpID]).ToArray(); foreach (var rEquipmentID in rData.ConsumedEquipmentID) { Equipment.Remove(rEquipmentID); } OnPropertyChanged(nameof(Equipment)); RemoveEquipmentFromUnequippedList(rConsumedEquipment); } }); ApiService.Subscribe("api_req_hokyu/charge", r => { var rData = r.GetData <RawSupplyResult>(); var rFleets = new HashSet <Fleet>(); Materials.Update(rData.Materials); foreach (var rShipSupplyResult in rData.Ships) { var rShip = Ships[rShipSupplyResult.ID]; rShip.Fuel.Current = rShipSupplyResult.Fuel; rShip.Bullet.Current = rShipSupplyResult.Bullet; if (rShip.OwnerFleet != null) { rFleets.Add(rShip.OwnerFleet); } var rPlanes = rShipSupplyResult.Planes; for (var i = 0; i < rShip.Slots.Count; i++) { var rCount = rPlanes[i]; if (rCount > 0) { rShip.Slots[i].PlaneCount = rCount; } } rShip.CombatAbility.Update(); } foreach (var rFleet in rFleets) { rFleet.Update(); } }); ApiService.Subscribe("api_req_air_corps/supply", r => { var rData = r.GetData <RawAirForceSquadronResupplyResult>(); Materials.Fuel = rData.Fuel; Materials.Bauxite = rData.Bauxite; }); ApiService.Subscribe("api_get_member/ndock", r => UpdateRepairDocks(r.GetData <RawRepairDock[]>())); ApiService.Subscribe("api_req_nyukyo/start", r => { var rShip = Ships[int.Parse(r.Parameters["api_ship_id"])]; var rIsInstantRepair = r.Parameters["api_highspeed"] == "1"; rShip.Repair(rIsInstantRepair); rShip.OwnerFleet?.Update(); var rDock = RepairDocks[int.Parse(r.Parameters["api_ndock_id"])]; rDock.PendingToUpdateMaterials = true; if (rIsInstantRepair) { Materials.Bucket--; } }); ApiService.Subscribe("api_req_nyukyo/speedchange", r => { Materials.Bucket--; RepairDocks[int.Parse(r.Parameters["api_ndock_id"])].CompleteRepair(); }); ApiService.Subscribe("api_req_combined_battle/battleresult", r => { var rData = (RawBattleResult)r.Data; if (!rData.HasEvacuatedShip) { return; } var rEvacuatedShipIndex = rData.EvacuatedShips.EvacuatedShipIndex[0] - 1; var rEvacuatedShipID = Fleets[rEvacuatedShipIndex < 6 ? 1 : 2].Ships[rEvacuatedShipIndex % 6].ID; var rEscortShipIndex = rData.EvacuatedShips.EscortShipIndex[0] - 1; var rEscortShipID = Fleets[rEscortShipIndex < 6 ? 1 : 2].Ships[rEscortShipIndex % 6].ID; r_EvacuatedShipIDs = new[] { rEvacuatedShipID, rEscortShipID }; }); ApiService.Subscribe("api_req_combined_battle/goback_port", delegate { if (SortieInfo.Current == null || r_EvacuatedShipIDs == null || r_EvacuatedShipIDs.Length == 0) { return; } EvacuatedShipIDs.Add(r_EvacuatedShipIDs[0]); EvacuatedShipIDs.Add(r_EvacuatedShipIDs[1]); }); ApiService.Subscribe("api_get_member/ship_deck", _ => r_EvacuatedShipIDs = null); ApiService.Subscribe("api_port/port", _ => EvacuatedShipIDs.Clear()); ApiService.Subscribe("api_req_member/updatedeckname", r => { var rFleet = Fleets[int.Parse(r.Parameters["api_deck_id"])]; rFleet.Name = r.Parameters["api_name"]; }); ApiService.Subscribe("api_req_mission/return_instruction", r => { var rFleet = Fleets[int.Parse(r.Parameters["api_deck_id"])]; rFleet.ExpeditionStatus.Update(r.GetData <RawExpeditionRecalling>().Expedition); }); ApiService.Subscribe("api_req_map/start", delegate { var rAirForceGroups = SortieInfo.Current?.AirForceGroups; if (rAirForceGroups == null) { return; } Materials.Fuel -= rAirForceGroups.Sum(r => r.LBASFuelConsumption); Materials.Bullet -= rAirForceGroups.Sum(r => r.LBASBulletConsumption); }); ApiService.Subscribe("api_req_air_corps/set_plane", r => Materials.Bauxite = r.GetData <RawAirForceGroupOrganization>().Bauxite); ApiService.Subscribe("api_req_hensei/lock", r => Ships[int.Parse(r.Parameters["api_ship_id"])].IsLocked = (bool)r.Json["api_data"]["api_locked"]); ApiService.Subscribe("api_req_kaisou/lock", r => Equipment[int.Parse(r.Parameters["api_slotitem_id"])].IsLocked = (bool)r.Json["api_data"]["api_locked"]); ApiService.Subscribe("api_get_member/useitem", r => UpdateItemCount((JArray)r.Json["api_data"])); }
public void AddFleet(Fleet f) { Fleets.Add(f); }
// Parses a game state from a string. On success, returns 1. On failure, // returns 0. private int ParseGameState(String s) { Planets.Clear(); Fleets.Clear(); ClearDupeCache(); //PORT: Make WindowsCompatible String[] lines = s.Replace("\r\n", "\n").Split('\n'); int planetid = 0; for (int i = 0; i < lines.Length; ++i) { String line = lines[i]; int commentBegin = line.IndexOf('#'); if (commentBegin >= 0) { line = line.Substring(0, commentBegin); } if (line.Trim().Length == 0) { continue; } String[] tokens = line.Split(' '); if (tokens.Length == 0) { continue; } if (tokens[0].Equals("P")) { if (tokens.Length != 6) { return(0); } double x = Double.parseDouble(tokens[1]); double y = Double.parseDouble(tokens[2]); int owner = Integer.parseInt(tokens[3]); int numShips = Integer.parseInt(tokens[4]); int growthRate = Integer.parseInt(tokens[5]); Planet p = new Planet(planetid++, owner, numShips, growthRate, x, y); Planets.Add(p); if (gamePlayback.Length > 0) { gamePlayback.Append(":"); } gamePlayback.Append("" + x + "," + y + "," + owner + "," + numShips + "," + growthRate); } else if (tokens[0].Equals("F")) { if (tokens.Length != 7) { return(0); } int owner = Integer.parseInt(tokens[1]); int numShips = Integer.parseInt(tokens[2]); int source = Integer.parseInt(tokens[3]); int destination = Integer.parseInt(tokens[4]); int totalTripLength = Integer.parseInt(tokens[5]); int turnsRemaining = Integer.parseInt(tokens[6]); Fleet f = new Fleet(owner, numShips, source, destination, totalTripLength, turnsRemaining); Fleets.Add(f); } else { return(0); } } gamePlayback.Append("|"); return(1); }
//Resolves the battle at planet p, if there is one. //* Removes all fleets involved in the battle //* Sets the number of ships and owner of the planet according the outcome private void FightBattle(Planet p) { Map <int, int> participants = new TreeMap <int, int>(); participants.put(p.Owner, p.NumShips); bool doBattle = false; //PORT: Deleting items from iterators is not allowed. // converted to deletable for loop for (int fleetIndex = 0; fleetIndex < Fleets.Count;) { Fleet fl = Fleets[fleetIndex]; if (fl.TurnsRemaining <= 0 && fl.DestinationPlanet == p.PlanetID) { int attackForce; doBattle = true; if (participants.TryGetValue(fl.Owner, out attackForce)) { participants[fl.Owner] = attackForce + fl.NumShips; } else { participants.Add(fl.Owner, fl.NumShips); } Fleets.Remove(fl); } else { fleetIndex++; } } if (doBattle) { Fleet winner = new Fleet(0, 0); Fleet second = new Fleet(0, 0); foreach (var f in participants) { if (f.Value > second.NumShips) { if (f.Value > winner.NumShips) { second = winner; winner = new Fleet(f.Key, f.Value); } else { second = new Fleet(f.Key, f.Value); } } } if (winner.NumShips > second.NumShips) { p.SetNumShips(winner.NumShips - second.NumShips); p.SetOwner(winner.Owner); } else { p.SetNumShips(0); } } }
internal Port() { SessionService.Instance.Subscribe("api_get_member/ship2", r => { UpdateShips(r.Json["api_data"].ToObject <RawShip[]>()); Fleets.Update(r.Json["api_data_deck"].ToObject <RawFleet[]>()); }); SessionService.Instance.Subscribe("api_get_member/ship_deck", r => { var rData = r.GetData <RawShipsAndFleets>(); foreach (var rRawShip in rData.Ships) { Ships[rRawShip.ID].Update(rRawShip); } var rRawFleet = rData.Fleets[0]; Fleets[rRawFleet.ID].Update(rRawFleet); OnPropertyChanged(nameof(Ships)); }); SessionService.Instance.Subscribe("api_get_member/ship3", r => { var rData = r.GetData <RawShipsAndFleets>(); foreach (var rShip in rData.Ships) { Ships[rShip.ID].Update(rShip); } Fleets.Update(rData.Fleets); ProcessUnequippedEquipment(r.Json["api_data"]["api_slot_data"]); }); SessionService.Instance.Subscribe("api_get_member/unsetslot", r => ProcessUnequippedEquipment(r.Json["api_data"])); SessionService.Instance.Subscribe("api_get_member/require_info", r => ProcessUnequippedEquipment(r.Json["api_data"]["api_unsetslot"])); SessionService.Instance.Subscribe("api_req_kaisou/slot_exchange_index", r => { Ship rShip; if (Ships.TryGetValue(int.Parse(r.Parameters["api_id"]), out rShip)) { rShip.UpdateEquipmentIDs(r.GetData <RawEquipmentIDs>().EquipmentIDs); rShip.OwnerFleet?.Update(); } }); SessionService.Instance.Subscribe("api_req_kaisou/open_exslot", r => { Ship rShip; if (Ships.TryGetValue(int.Parse(r.Parameters["api_id"]), out rShip)) { rShip.InstallReinforcementExpansion(); } }); SessionService.Instance.Subscribe("api_req_kaisou/slot_deprive", r => { var rData = r.GetData <RawEquipmentRelocationResult>(); var rDestionationShip = Ships[rData.Ships.Destination.ID]; var rOriginShip = Ships[rData.Ships.Origin.ID]; rDestionationShip.Update(rData.Ships.Destination); rOriginShip.Update(rData.Ships.Origin); rDestionationShip.OwnerFleet?.Update(); rOriginShip.OwnerFleet?.Update(); if (rData.UnequippedEquipment != null) { UnequippedEquipment[(EquipmentType)rData.UnequippedEquipment.Type] = rData.UnequippedEquipment.IDs.Select(rpID => Equipment[rpID]).ToArray(); } }); SessionService.Instance.Subscribe("api_req_kaisou/powerup", r => { var rShipID = int.Parse(r.Parameters["api_id"]); var rData = r.GetData <RawModernizationResult>(); Ship rModernizedShip; if (Ships.TryGetValue(rShipID, out rModernizedShip)) { rModernizedShip.Update(rData.Ship); } var rConsumedShips = r.Parameters["api_id_items"].Split(',').Select(rpID => Ships[int.Parse(rpID)]).ToArray(); var rConsumedEquipment = rConsumedShips.SelectMany(rpShip => rpShip.EquipedEquipment).ToArray(); foreach (var rEquipment in rConsumedEquipment) { Equipment.Remove(rEquipment); } foreach (var rShip in rConsumedShips) { Ships.Remove(rShip); } RemoveEquipmentFromUnequippedList(rConsumedEquipment); RecordService.Instance?.Fate?.AddShipFate(rConsumedShips, Fate.ConsumedByModernization); UpdateShipsCore(); OnPropertyChanged(nameof(Equipment)); Fleets.Update(rData.Fleets); }); SessionService.Instance.Subscribe("api_req_kousyou/createship", r => ConstructionDocks[int.Parse(r.Parameters["api_kdock_id"])].IsConstructionStarted = true); SessionService.Instance.Subscribe("api_req_kousyou/getship", r => { var rData = r.GetData <RawConstructionResult>(); UpdateConstructionDocks(rData.ConstructionDocks); AddEquipment(rData.Equipment); Ships.Add(new Ship(rData.Ship)); UpdateShipsCore(); }); SessionService.Instance.Subscribe("api_req_kousyou/createship_speedchange", r => { if (r.Parameters["api_highspeed"] == "1") { var rDock = ConstructionDocks[int.Parse(r.Parameters["api_kdock_id"])]; if (!rDock.IsLargeShipConstruction.GetValueOrDefault()) { Materials.InstantConstruction--; } else { Materials.InstantConstruction -= 10; } rDock.CompleteConstruction(); } }); SessionService.Instance.Subscribe("api_req_kousyou/createitem", r => { var rData = r.GetData <RawEquipmentDevelopment>(); if (!rData.Success) { return; } UnequippedEquipment[(EquipmentType)rData.EquipmentType] = r.Json["api_data"]["api_unsetslot"].Select(rpID => Equipment[(int)rpID]).ToArray(); }); SessionService.Instance.Subscribe("api_req_kousyou/destroyship", r => { Materials.Update(r.Json["api_data"]["api_material"].ToObject <int[]>()); var rShip = Ships[int.Parse(r.Parameters["api_ship_id"])]; RecordService.Instance?.Fate?.AddShipFate(rShip, Fate.Dismantled); foreach (var rEquipment in rShip.EquipedEquipment) { Equipment.Remove(rEquipment); } OnPropertyChanged(nameof(Equipment)); RemoveEquipmentFromUnequippedList(rShip.EquipedEquipment); rShip.OwnerFleet?.Remove(rShip); Ships.Remove(rShip); UpdateShipsCore(); }); SessionService.Instance.Subscribe("api_req_kousyou/destroyitem2", r => { var rEquipmentIDs = r.Parameters["api_slotitem_ids"].Split(',').Select(int.Parse); RecordService.Instance?.Fate?.AddEquipmentFate(rEquipmentIDs.Select(rpID => Equipment[rpID]), Fate.Scrapped); foreach (var rEquipmentID in rEquipmentIDs) { Equipment.Remove(rEquipmentID); } OnPropertyChanged(nameof(Equipment)); var rMaterials = r.Json["api_data"]["api_get_material"].ToObject <int[]>(); Materials.Fuel += rMaterials[0]; Materials.Bullet += rMaterials[1]; Materials.Steel += rMaterials[2]; Materials.Bauxite += rMaterials[3]; }); SessionService.Instance.Subscribe("api_req_kousyou/remodel_slot", r => { var rData = (RawImprovementResult)r.Data; Materials.Update(rData.Materials); Equipment rEquipment; if (rData.Success && Equipment.TryGetValue(rData.ImprovedEquipment.ID, out rEquipment)) { rEquipment.Update(rData.ImprovedEquipment); } if (rData.ConsumedEquipmentID != null) { var rConsumedEquipment = rData.ConsumedEquipmentID.Select(rpID => Equipment[rpID]).ToArray(); RecordService.Instance?.Fate?.AddEquipmentFate(rConsumedEquipment, Fate.ConsumedByImprovement); foreach (var rEquipmentID in rData.ConsumedEquipmentID) { Equipment.Remove(rEquipmentID); } OnPropertyChanged(nameof(Equipment)); RemoveEquipmentFromUnequippedList(rConsumedEquipment); } }); SessionService.Instance.Subscribe("api_req_hokyu/charge", r => { var rData = r.GetData <RawSupplyResult>(); var rFleets = new HashSet <Fleet>(); Materials.Update(rData.Materials); foreach (var rShipSupplyResult in rData.Ships) { var rShip = Ships[rShipSupplyResult.ID]; rShip.Fuel = rShip.Fuel.Update(rShipSupplyResult.Fuel); rShip.Bullet = rShip.Bullet.Update(rShipSupplyResult.Bullet); if (rShip.OwnerFleet != null) { rFleets.Add(rShip.OwnerFleet); } var rPlanes = rShipSupplyResult.Planes; for (var i = 0; i < rShip.Slots.Count; i++) { var rCount = rPlanes[i]; if (rCount > 0) { rShip.Slots[i].PlaneCount = rCount; } } rShip.CombatAbility.Update(); } foreach (var rFleet in rFleets) { rFleet.Update(); } }); SessionService.Instance.Subscribe("api_req_air_corps/supply", r => { var rData = r.GetData <RawAirForceSquadronResupplyResult>(); Materials.Fuel = rData.Fuel; Materials.Bauxite = rData.Bauxite; }); SessionService.Instance.Subscribe("api_get_member/ndock", r => UpdateRepairDocks(r.GetData <RawRepairDock[]>())); SessionService.Instance.Subscribe("api_req_nyukyo/start", r => { var rShip = Ships[int.Parse(r.Parameters["api_ship_id"])]; var rIsInstantRepair = r.Parameters["api_highspeed"] == "1"; rShip.Repair(rIsInstantRepair); rShip.OwnerFleet?.Update(); var rDock = RepairDocks[int.Parse(r.Parameters["api_ndock_id"])]; rDock.PendingToUpdateMaterials = true; if (rIsInstantRepair) { Materials.Bucket--; } }); SessionService.Instance.Subscribe("api_req_nyukyo/speedchange", r => { Materials.Bucket--; RepairDocks[int.Parse(r.Parameters["api_ndock_id"])].CompleteRepair(); }); SessionService.Instance.Subscribe("api_req_combined_battle/battleresult", r => { var rData = (RawBattleResult)r.Data; if (!rData.HasEvacuatedShip) { return; } var rEvacuatedShipIndex = rData.EvacuatedShips.EvacuatedShipIndex[0] - 1; var rEvacuatedShipID = Fleets[rEvacuatedShipIndex < 6 ? 1 : 2].Ships[rEvacuatedShipIndex % 6].ID; var rEscortShipIndex = rData.EvacuatedShips.EscortShipIndex[0] - 1; var rEscortShipID = Fleets[rEscortShipIndex < 6 ? 1 : 2].Ships[rEscortShipIndex % 6].ID; r_EvacuatedShipIDs = new[] { rEvacuatedShipID, rEscortShipID }; }); SessionService.Instance.Subscribe("api_req_combined_battle/goback_port", delegate { if (SortieInfo.Current == null || r_EvacuatedShipIDs == null || r_EvacuatedShipIDs.Length == 0) { return; } EvacuatedShipIDs.Add(r_EvacuatedShipIDs[0]); EvacuatedShipIDs.Add(r_EvacuatedShipIDs[1]); }); SessionService.Instance.Subscribe("api_get_member/ship_deck", _ => r_EvacuatedShipIDs = null); SessionService.Instance.Subscribe("api_port/port", _ => EvacuatedShipIDs.Clear()); SessionService.Instance.Subscribe("api_req_member/updatedeckname", r => { var rFleet = Fleets[int.Parse(r.Parameters["api_deck_id"])]; rFleet.Name = r.Parameters["api_name"]; }); SessionService.Instance.Subscribe("api_req_mission/return_instruction", r => { var rFleet = Fleets[int.Parse(r.Parameters["api_deck_id"])]; rFleet.ExpeditionStatus.Update(r.GetData <RawExpeditionRecalling>().Expedition); }); SessionService.Instance.Subscribe("api_req_air_corps/set_plane", r => Materials.Bauxite = r.GetData <RawAirForceGroupOrganization>().Bauxite); SessionService.Instance.Subscribe("api_req_hensei/lock", r => Ships[int.Parse(r.Parameters["api_ship_id"])].IsLocked = (bool)r.Json["api_data"]["api_locked"]); SessionService.Instance.Subscribe("api_req_kaisou/lock", r => Equipment[int.Parse(r.Parameters["api_slotitem_id"])].IsLocked = (bool)r.Json["api_data"]["api_locked"]); }
private IEnumerable <Fleet> _getFleetsForPlayer(int id) { return(Fleets.Where(f => f.OwnerId == id)); }
// ReSharper disable once InconsistentNaming private void initializeAPI() { Alliance = new Alliance(dataSource) { HTTP = http }; Assets = new Assets(dataSource) { HTTP = http }; Bookmarks = new Bookmarks(dataSource) { HTTP = http }; Calendar = new Calendar(dataSource) { HTTP = http }; Character = new Character(dataSource) { HTTP = http }; Clones = new Clones(dataSource) { HTTP = http }; Contacts = new Contacts(dataSource) { HTTP = http }; Contracts = new Contracts(dataSource) { HTTP = http }; Corporation = new Corporation(dataSource) { HTTP = http }; Dogma = new Dogma(dataSource) { HTTP = http }; FactionWarfare = new FactionWarfare(dataSource) { HTTP = http }; Fittings = new Fittings(dataSource) { HTTP = http }; Fleets = new Fleets(dataSource) { HTTP = http }; Incursion = new Incursions(dataSource) { HTTP = http }; Industry = new Industry(dataSource) { HTTP = http }; Insurance = new Insurance(dataSource) { HTTP = http }; Killmails = new Killmails(dataSource) { HTTP = http }; Location = new Location(dataSource) { HTTP = http }; Loyalty = new Loyalty(dataSource) { HTTP = http }; Mail = new Mail(dataSource) { HTTP = http }; Market = new Market(dataSource) { HTTP = http }; Opportunities = new Opportunities(dataSource) { HTTP = http }; PlanetaryInteraction = new PlanetaryInteraction(dataSource) { HTTP = http }; Routes = new Routes(dataSource) { HTTP = http }; Search = new Search(dataSource) { HTTP = http }; Skills = new Skills(dataSource) { HTTP = http }; Sovereignty = new Sovereignty(dataSource) { HTTP = http }; Status = new Status(dataSource) { HTTP = http }; Universe = new Universe(dataSource) { HTTP = http }; UserInterface = new UserInterface(dataSource) { HTTP = http }; Wallet = new Wallet(dataSource) { HTTP = http }; Wars = new Wars(dataSource) { HTTP = http }; }
public void Update(DateTime currentTime) { if (this.Waiting) { if (currentTime > gameStart) { if (Players.Count == 2) { this.Waiting = false; } else { if (currentTime > gameQuit) { this.Waiting = false; this.Status = "Nobody joined your game, I guess that means you win."; GameOver = true; } else { UpdateTimeInfo(gameStart.AddSeconds(2)); } } } return; } if (GameOver) { this.Stop(); return; } // check if we are in the server window if (currentTime >= endPlayerTurn) { // server processing Processing = true; // Grow ships on planets foreach (var planet in Planets) { // if the planet is not controlled by neutral update if (planet.OwnerId != -1) { planet.NumberOfShips += planet.GrowthRate; } } // Send fleets foreach (var fleet in Fleets) { // travel 1 unit distance each turn fleet.NumberOfTurnsToDestination--; } // Resolve planet battles foreach (var planet in Planets) { var combatants = new Dictionary <int, int>(); combatants.Add(planet.OwnerId, planet.NumberOfShips); // find fleets destined for this planet var fleets = Fleets.Where(f => f.Destination.Id == planet.Id && f.NumberOfTurnsToDestination <= 0); foreach (var fleet in fleets) { if (combatants.ContainsKey(fleet.OwnerId)) { combatants[fleet.OwnerId] += fleet.NumberOfShips; } else { combatants.Add(fleet.OwnerId, fleet.NumberOfShips); } } if (fleets.Count() <= 0) { continue; } KeyValuePair <int, int> second = new KeyValuePair <int, int>(1, 0); KeyValuePair <int, int> winner = new KeyValuePair <int, int>(2, 0); foreach (var keyval in combatants) { if (keyval.Value > second.Value) { if (keyval.Value > winner.Value) { second = winner; winner = keyval; } else { second = keyval; } } } if (winner.Value > second.Value) { planet.NumberOfShips = winner.Value - second.Value; planet.OwnerId = winner.Key; } else { planet.NumberOfShips = 0; } } // remove finished fleets lock (synclock) { _fleets.RemoveAll(f => f.NumberOfTurnsToDestination <= 0); } // Check game over conditions var player1NoPlanets = !Planets.Any(p => p.OwnerId == 1); var player1NoShips = !Fleets.Any(f => f.OwnerId == 1); var player2NoPlanet = !Planets.Any(p => p.OwnerId == 2); var player2NoShips = !Fleets.Any(f => f.OwnerId == 2); if (player1NoPlanets && player1NoShips) { // player 2 has won var winner = Players.Values.FirstOrDefault(p => p.Id == 2); var loser = Players.Values.FirstOrDefault(p => p.Id == 1); this.Status = $"{winner?.PlayerName} has defeated {loser?.PlayerName}!"; this.GameOver = true; } if (player2NoPlanet && player2NoShips) { // player 1 has won var winner = Players.Values.FirstOrDefault(p => p.Id == 1); var loser = Players.Values.FirstOrDefault(p => p.Id == 2); this.Status = $"{winner?.PlayerName} has defeated {loser?.PlayerName}!"; this.GameOver = true; } PlayerAScoreOverTime.Add(_getPlayerScore(1)); PlayerBScoreOverTime.Add(_getPlayerScore(2)); // Turn complete Turn++; endPlayerTurn = currentTime.AddMilliseconds(PLAYER_TURN_LENGTH); endServerTurn = endPlayerTurn.AddMilliseconds(SERVER_TURN_LENGTH); Processing = false; System.Diagnostics.Debug.WriteLine($"Game {Id} : Turn {Turn} : Next Turn Start {endServerTurn.Subtract(DateTime.UtcNow).TotalMilliseconds}ms"); } if (Turn >= MAX_TURN) { var player1 = _getPlayerForId(1)?.PlayerName; var player2 = _getPlayerForId(2)?.PlayerName; var player1Score = _getPlayerScore(1); var player2Score = _getPlayerScore(2); if (player1Score == player2Score) { this.Status = $"{player1} has tied {player2}!"; } else if (player1Score > player2Score) { this.Status = $"{player1} has defeated {player2}!"; } else { this.Status = $"{player2} has defeated {player1}!"; } this.GameOver = true; } }
public void AddFleet(Fleet fleet) { Fleets.Add(fleet); }
public override void LoadFromResponse(string apiname, dynamic data) { switch (apiname) { case "api_req_sortie/goback_port": case "api_req_combined_battle/goback_port": { var battle = KCDatabase.Instance.Battle; foreach (int ii in battle.Result.EscapingShipIndex) { int index = ii - 1; if (index < battle.FirstBattle.Initial.FriendFleet.Members.Count) { battle.FirstBattle.Initial.FriendFleet.Escape(index); } else { battle.FirstBattle.Initial.FriendFleetEscort.Escape(index - 6); } } } break; case "api_get_member/ndock": foreach (var fleet in Fleets.Values) { fleet.LoadFromResponse(apiname, data); } break; case "api_req_hensei/preset_select": { int id = (int)data.api_id; if (!Fleets.ContainsKey(id)) { var a = new FleetData(); a.LoadFromResponse(apiname, data); Fleets.Add(a); } else { Fleets[id].LoadFromResponse(apiname, data); } } break; default: base.LoadFromResponse(apiname, (object)data); //api_port/port, api_get_member/deck foreach (var elem in data) { int id = (int)elem.api_id; if (!Fleets.ContainsKey(id)) { var a = new FleetData(); a.LoadFromResponse(apiname, elem); Fleets.Add(a); } else { Fleets[id].LoadFromResponse(apiname, elem); } } break; } // 泊地修理・コンディションの処理 if (apiname == "api_port/port") { if ((DateTime.Now - AnchorageRepairingTimer).TotalMinutes >= 20) { StartAnchorageRepairingTimer(); } else { CheckAnchorageRepairingHealing(); } UpdateConditionPrediction(); } }
public void AddFleets(IEnumerable <Fleet> fleets) { Fleets.AddRange(fleets); }