public ActionResult CounterProposal(int id) { var db = new ZkDataContext(); var treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == id); var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); if (treaty.CanCancel(acc) && treaty.TreatyState == TreatyState.Proposed) { if (treaty.AcceptingFactionGuarantee == acc.FactionID) { var pom = treaty.AcceptingFactionGuarantee; treaty.AcceptingFactionGuarantee = treaty.ProposingFactionGuarantee; treaty.ProposingFactionGuarantee = pom; } treaty.FactionByAcceptingFactionID = treaty.AcceptingFactionID == acc.FactionID ? treaty.FactionByProposingFactionID : treaty.FactionByAcceptingFactionID; treaty.AccountByProposingAccountID = acc; treaty.FactionByProposingFactionID = acc.Faction; treaty.TreatyState = TreatyState.Invalid; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} modified treaty proposal {1} between {2} and {3}", acc, treaty, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID)); db.SaveChanges(); return(View("FactionTreatyDefinition", db.FactionTreaties.Find(treaty.FactionTreatyID))); } return(Content("Not permitted")); }
public ActionResult JoinFaction(int id) { if (Global.Account.FactionID != null) { return(Content("Already in faction")); } if (Global.Account.Clan != null && Global.Account.Clan.FactionID != id) { return(Content("Must leave current clan first")); } var db = new ZkDataContext(); Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); acc.FactionID = id; Faction faction = db.Factions.Single(x => x.FactionID == id); if (faction.IsDeleted && !(Global.Account.Clan != null && Global.Account.Clan.FactionID == id)) { throw new ApplicationException("Cannot join deleted faction"); } db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} joins {1}", acc, faction)); db.SaveChanges(); Global.Server.PublishAccountUpdate(acc); return(RedirectToAction("Index", "Factions")); }
public ActionResult RushActivation(int planetID, int structureTypeID) { using (var db = new ZkDataContext()) { var planet = db.Planets.Single(p => p.PlanetID == planetID); var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); var structure = planet.PlanetStructures.Single(x => x.StructureTypeID == structureTypeID); if (structure.RushStructure(acc)) { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} has rushed activation of {1} on {2} planet {3}.", acc, structure.StructureType, planet.Faction, planet)); } else { return(Content("You cannot rush this")); } db.SaveChanges(); return(RedirectToAction("Planet", new { id = planetID })); } }
public ActionResult SetStructureTarget(int planetID, int structureTypeID, int targetPlanetID) { var db = new ZkDataContext(); var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); var planet = db.Planets.Single(x => x.PlanetID == planetID); var structure = planet.PlanetStructures.Single(x => x.StructureTypeID == structureTypeID); if (!acc.CanSetStructureTarget(structure)) { return(Content("Cannot set target")); } var target = db.Planets.Single(x => x.PlanetID == targetPlanetID); if (target != structure.PlanetByTargetPlanetID) { structure.ReactivateAfterBuild(); } structure.PlanetByTargetPlanetID = target; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} of {1} aimed {2} located at {3} to {4} planet {5}", acc, acc.Faction, structure.StructureType, planet, target.Faction, target)); if (structure.IsActive && !structure.StructureType.IsSingleUse) { return(ActivateTargetedStructure(planetID, structureTypeID)); } db.SaveChanges(); return(RedirectToAction("Planet", new { id = planet.PlanetID })); }
public ActionResult SubmitRenamePlanet(int planetID, string newName, int teamSize, string map) { using (var scope = new TransactionScope()) { if (String.IsNullOrWhiteSpace(newName)) { return(Content("Error: the planet must have a name.")); } var db = new ZkDataContext(); var acc = db.Accounts.Find(Global.AccountID); Planet planet = db.Planets.Single(p => p.PlanetID == planetID); if (planet.Name != newName) { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} renamed planet {1} to {2}", acc, planet, newName)); } db.SaveChanges(); planet.Name = newName; planet.TeamSize = teamSize; planet.Resource = db.Resources.Where(x => x.TypeID == ResourceType.Map && x.InternalName == map).First(); planet.Galaxy.IsDirty = true; db.SaveChanges(); scope.Complete(); return(RedirectToAction("Planet", new { id = planet.PlanetID })); } }
/// <summary> /// Clan leaving logic (including after kick) /// </summary> public static Clan PerformLeaveClan(int accountID, ZkDataContext db = null) { if (db == null) { db = new ZkDataContext(); } var acc = db.Accounts.Single(x => x.AccountID == accountID); var clan = acc.Clan; if (clan == null) { return(null); // Person not in a clan } RoleType leader = db.RoleTypes.FirstOrDefault(x => x.RightKickPeople && x.IsClanOnly); bool isLeader = acc.AccountRolesByAccountID.Any(x => x.RoleType == leader); // remove role db.AccountRoles.DeleteAllOnSubmit(acc.AccountRolesByAccountID.Where(x => x.RoleType.IsClanOnly).ToList()); // delete active polls db.Polls.DeleteAllOnSubmit(acc.PollsByRoleTargetAccountID.Where(x => x.RoleType.IsClanOnly)); // remove planets acc.Planets.Clear(); acc.ResetQuotas(); // delete channel subscription //if (!acc.IsZeroKAdmin || acc.IsZeroKAdmin) //{ // var channelSub = db.LobbyChannelSubscriptions.FirstOrDefault(x => x.Account == acc && x.Channel == acc.Clan.GetClanChannel()); // db.LobbyChannelSubscriptions.DeleteOnSubmit(channelSub); //} acc.Clan = null; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} leaves clan {1}", acc, clan)); db.SaveChanges(); if (!clan.Accounts.Any()) { clan.IsDeleted = true; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} is disbanded", clan)); } else if (isLeader) { var otherClanMember = clan.Accounts.FirstOrDefault(x => x.AccountID != accountID); if (otherClanMember != null) { db.AccountRoles.InsertOnSubmit(new AccountRole() { AccountID = otherClanMember.AccountID, Clan = clan, RoleType = leader, Inauguration = DateTime.UtcNow }); } } db.SaveChanges(); Global.Server.PublishAccountUpdate(acc); return(clan); }
public ActionResult DestroyStructure(int planetID, int structureTypeID) { using (var db = new ZkDataContext()) { Planet planet = db.Planets.Single(p => p.PlanetID == planetID); if (Global.Server.GetPlanetBattles(planet).Any(x => x.IsInGame)) { return(Content("Battle in progress on the planet, cannot destroy structures")); } Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); StructureType structureType = db.StructureTypes.SingleOrDefault(s => s.StructureTypeID == structureTypeID); Faction faction = planet.Faction; if (structureType == null) { return(Content("Structure type does not exist.")); } if (!structureType.IsBuildable) { return(Content("Structure is not buildable.")); } // assumes you can only build level 1 structures! if higher level structures can be built directly, we should check down the upgrade chain too if (!planet.PlanetStructures.Any(x => x.StructureTypeID == structureTypeID)) { return(Content("Structure or its upgrades not present")); } List <PlanetStructure> list = planet.PlanetStructures.Where(x => x.StructureTypeID == structureTypeID).ToList(); PlanetStructure toDestroy = list[0]; if (!toDestroy.IsActive) { return(Content("Structure is currently disabled")); } var canDestroy = toDestroy.OwnerAccountID == acc.AccountID || planet.OwnerAccountID == acc.AccountID; if (!canDestroy) { return(Content("Structure is not under your control.")); } var refund = toDestroy.StructureType.Cost * GlobalConst.SelfDestructRefund; if (toDestroy.Account != null) { toDestroy.Account.ProduceMetal(refund); } else { faction?.ProduceMetal(refund); } db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} has demolished a {1} on {2}.", acc, toDestroy.StructureType, planet)); db.PlanetStructures.DeleteOnSubmit(toDestroy); db.SaveChanges(); PlanetWarsTurnHandler.SetPlanetOwners(new PlanetwarsEventCreator(), db); } return(RedirectToAction("Planet", new { id = planetID })); }
public ActionResult AppointRole(int accountID, int roletypeID) { var db = new ZkDataContext(); Account targetAccount = db.Accounts.Single(x => x.AccountID == accountID); Account myAccount = db.Accounts.Single(x => x.AccountID == Global.AccountID); RoleType role = db.RoleTypes.Single(x => x.RoleTypeID == roletypeID); if (myAccount.CanAppoint(targetAccount, role)) { Account previous = null; if (role.IsOnePersonOnly) { List <AccountRole> entries = db.AccountRoles.Where( x => x.RoleTypeID == role.RoleTypeID && (role.IsClanOnly ? x.ClanID == myAccount.ClanID : x.FactionID == myAccount.FactionID)).ToList(); if (entries.Any()) { previous = entries.First().Account; db.AccountRoles.DeleteAllOnSubmit(entries); } } var entry = new AccountRole { AccountID = accountID, Inauguration = DateTime.UtcNow, Clan = role.IsClanOnly ? myAccount.Clan : null, Faction = !role.IsClanOnly ? myAccount.Faction : null, RoleTypeID = roletypeID, }; db.AccountRoles.InsertOnSubmit(entry); if (previous != null) { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} was appointed to the {1} role of {2} by {3} - replacing {4}", targetAccount, role.IsClanOnly ? (object)myAccount.Clan : myAccount.Faction, role, myAccount, previous)); } else { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} was appointed to the {1} role of {2} by {3}", targetAccount, role.IsClanOnly ? (object)myAccount.Clan : myAccount.Faction, role, myAccount)); } Global.Server.GhostPm(targetAccount.Name, string.Format("You were appointed for the function of {0} by {1}", role.Name, myAccount.Name)); db.SaveChanges(); return(RedirectToAction("Detail", "Users", new { id = accountID })); } else { return(Content("Cannot recall")); } }
public ActionResult BuildStructure(int planetID, int structureTypeID) { using (var db = new ZkDataContext()) { Planet planet = db.Planets.Single(p => p.PlanetID == planetID); if (Global.Server.GetPlanetBattles(planet).Any(x => x.IsInGame)) { return(Content("Battle in progress on the planet, cannot build structures")); } Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); if (acc.FactionID != planet.OwnerFactionID) { return(Content("Planet is not under your control.")); } StructureType structureType = db.StructureTypes.SingleOrDefault(s => s.StructureTypeID == structureTypeID); if (structureType == null) { return(Content("Structure type does not exist.")); } if (!structureType.IsBuildable) { return(Content("Structure is not buildable.")); } if (acc.GetMetalAvailable() < structureType.Cost) { return(Content("Insufficient metal")); } acc.SpendMetal(structureType.Cost); var newBuilding = new PlanetStructure { StructureTypeID = structureTypeID, StructureType = structureType, PlanetID = planetID, OwnerAccountID = acc.AccountID, }; newBuilding.ReactivateAfterBuild(); db.PlanetStructures.InsertOnSubmit(newBuilding); db.SaveChanges(); db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} has built a {1} on {2} planet {3}.", acc, newBuilding.StructureType, planet.Faction, planet)); PlanetWarsTurnHandler.SetPlanetOwners(new PlanetwarsEventCreator(), db); } return(RedirectToAction("Planet", new { id = planetID })); }
private ActionResult FirePlanetBuster(int planetID, int structureTypeID, int targetID) { var db = new ZkDataContext(); PlanetStructure structure = db.PlanetStructures.FirstOrDefault(x => x.PlanetID == planetID && x.StructureTypeID == structureTypeID); Planet source = db.Planets.FirstOrDefault(x => x.PlanetID == planetID); Planet target = db.Planets.FirstOrDefault(x => x.PlanetID == targetID); Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); if (acc.Faction == null) { return(Content("Join some faction first")); } if (!target.CanFirePlanetBuster(acc.Faction)) { return(Content("You cannot attack here")); } //Get rid of all strutures var structures = target.PlanetStructures.Where(x => x.StructureType.EffectIsVictoryPlanet != true && x.StructureType.OwnerChangeWinsGame != true).ToList(); //kill all IP foreach (var pf in target.PlanetFactions.Where(x => x.Influence > 0)) { pf.Influence = 0; } var links = db.Links.Where(x => (x.PlanetID1 == target.PlanetID || x.PlanetID2 == target.PlanetID)); foreach (Link link in links) { db.Links.DeleteOnSubmit(link); } db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("A {4} fired from {0} {1} has destroyed {2} {3}!", source.Faction, source, target.Faction, target, structure.StructureType)); db.SaveChanges(); db.PlanetStructures.DeleteAllOnSubmit(structures); var residue = db.StructureTypes.First(x => x.Name == "Residue"); // todo not nice use constant instead target.PlanetStructures.Add(new PlanetStructure() { StructureType = residue, IsActive = true, ActivatedOnTurn = null }); db.SaveChanges(); return(null); }
public ActionResult CancelTreaty(int id) { var db = new ZkDataContext(); var treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == id); var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); if (treaty.CanCancel(acc)) { treaty.TreatyState = TreatyState.Invalid; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("Treaty {0} between {1} and {2} cancelled by {3}", treaty, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID, acc)); db.SaveChanges(); return(RedirectToAction("Detail", new { id = Global.FactionID })); } return(Content("Cannot cancel")); }
public ActionResult SetEnergyPriority(int planetID, int structuretypeID, EnergyPriority priority) { var db = new ZkDataContext(); var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); var planet = db.Planets.Single(x => x.PlanetID == planetID); var structure = planet.PlanetStructures.Single(x => x.StructureTypeID == structuretypeID); if (!acc.CanSetPriority(structure)) { return(Content("Cannot set priority")); } structure.EnergyPriority = priority; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} changed energy priority of {1} on {2} to {3}", acc, structure.StructureType, planet, priority)); db.SaveChanges(); return(RedirectToAction("Planet", new { id = planet.PlanetID })); }
// GET: PlanetwarsAdmin public ActionResult Index(PlanetwarsAdminModel model, string set, string purge, string futureset) { var db = new ZkDataContext(); if (model != null) { if (!string.IsNullOrEmpty(set)) { MiscVar.PlanetWarsMode = model.PlanetWarsMode; db.Events.Add(PlanetwarsEventCreator.CreateEvent("{0} changed PlanetWars status to {1}", db.Accounts.Find(Global.AccountID), model.PlanetWarsMode.Description())); db.SaveChanges(); } if (!string.IsNullOrEmpty(purge)) { PurgeGalaxy(model.LastSelectedGalaxyID, model.UnassignFactions, model.ResetRoles, model.DeleteClans); } if (!string.IsNullOrEmpty(futureset)) { if (model.PlanetWarsNextMode == MiscVar.PlanetWarsMode || model.PlanetWarsNextModeDate == null || model.PlanetWarsNextModeDate < DateTime.UtcNow || model.PlanetWarsNextMode == null) { model.PlanetWarsNextMode = null; model.PlanetWarsNextModeDate = null; } MiscVar.PlanetWarsNextMode = model.PlanetWarsNextMode; MiscVar.PlanetWarsNextModeTime = model.PlanetWarsNextModeDate; } } model = model ?? new PlanetwarsAdminModel(); model.PlanetWarsMode = MiscVar.PlanetWarsMode; model.PlanetWarsNextMode = MiscVar.PlanetWarsNextMode; model.PlanetWarsNextModeDate = MiscVar.PlanetWarsNextModeTime; model.Galaxies = db.Galaxies.OrderByDescending(x => x.IsDefault).ThenByDescending(x => x.GalaxyID); model.LastSelectedGalaxyID = model.Galaxies.FirstOrDefault(x => x.IsDefault)?.GalaxyID ?? 0; return(View("PlanetwarsAdminIndex", model)); }
public static Faction PerformLeaveFaction(int accountID, bool keepClan = false, ZkDataContext db = null) { if (db == null) { db = new ZkDataContext(); } Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); Faction faction = acc.Faction; if (!keepClan && acc.Clan != null) { ClansController.PerformLeaveClan(Global.AccountID); } db.AccountRoles.DeleteAllOnSubmit(acc.AccountRolesByAccountID.Where(x => !keepClan || x.ClanID == null).ToList()); acc.ResetQuotas(); foreach (var ps in acc.PlanetStructures) { ps.OwnerAccountID = null; } foreach (var planet in acc.Planets) { planet.OwnerAccountID = null; } db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} leaves faction {1}", acc, acc.Faction)); db.SaveChanges(); PlanetWarsTurnHandler.SetPlanetOwners(new PlanetwarsEventCreator(), db); using (var db2 = new ZkDataContext()) { Account acc2 = db2.Accounts.Single(x => x.AccountID == Global.AccountID); acc2.FactionID = null; db2.SaveChanges(); Global.Server.PublishAccountUpdate(acc2); Global.Server.PublishUserProfileUpdate(acc2); PlanetWarsTurnHandler.SetPlanetOwners(new PlanetwarsEventCreator(), db2); } return(faction); }
public ActionResult ConfiscateStructure(int planetID, int structureTypeID) { using (var db = new ZkDataContext()) { Planet planet = db.Planets.Single(p => p.PlanetID == planetID); //if (Global.Nightwatch.GetPlanetBattles(planet).Any(x => x.IsInGame)) return Content("Battle in progress on the planet, cannot destroy structures"); Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); bool factionLeader = acc.HasFactionRight(x => x.RightMetalQuota > 0) && (acc.Faction == planet.Faction); if ((planet.OwnerAccountID != acc.AccountID) && !factionLeader) { return(Content("Planet not yours")); } StructureType structureType = db.StructureTypes.SingleOrDefault(s => s.StructureTypeID == structureTypeID); if (structureType == null) { return(Content("Structure type does not exist.")); } //if (!structureType.IsBuildable) return Content("Structure is not buildable."); if (!planet.PlanetStructures.Any(x => x.StructureTypeID == structureTypeID)) { return(Content("Structure or its upgrades not present")); } List <PlanetStructure> list = planet.PlanetStructures.Where(x => x.StructureTypeID == structureTypeID).ToList(); PlanetStructure structure = list[0]; Account orgAc = structure.Account; double cost = (!factionLeader) ? structure.StructureType.Cost : 0; if (orgAc != null) { structure.Account.SpendMetal(-cost); acc.SpendMetal(cost); } structure.Account = acc; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} has confiscated {1} structure {2} on {3}.", acc, orgAc, structure.StructureType, planet)); db.SaveChanges(); return(RedirectToAction("Planet", new { id = planetID })); } }
public ActionResult RecallRole(int accountID, int roletypeID) { var db = new ZkDataContext(); Account targetAccount = db.Accounts.Single(x => x.AccountID == accountID); Account myAccount = db.Accounts.Single(x => x.AccountID == Global.AccountID); RoleType role = db.RoleTypes.Single(x => x.RoleTypeID == roletypeID); if (myAccount.CanRecall(targetAccount, role)) { db.AccountRoles.DeleteAllOnSubmit(db.AccountRoles.Where(x => x.AccountID == accountID && x.RoleTypeID == roletypeID)); db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} was recalled from the {1} role of {2} by {3}", targetAccount, role.IsClanOnly ? (object)myAccount.Clan : myAccount.Faction, role, myAccount)); Global.Server.GhostPm(targetAccount.Name, string.Format("You were recalled from the function of {0} by {1}", role.Name, myAccount.Name)); db.SaveChanges(); return(RedirectToAction("Detail", "Users", new { id = accountID })); } else { return(Content("Cannot recall")); } }
public ActionResult JoinClan(int id, string password) { var db = new ZkDataContext(); var clan = db.Clans.Single(x => x.ClanID == id); if (clan.CanJoin(Global.Account)) { if (!string.IsNullOrEmpty(clan.Password) && clan.Password != password) { return(View(clan.ClanID)); } else { var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); acc.ClanID = clan.ClanID; acc.FactionID = clan.FactionID; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} joins clan {1}", acc, clan)); if (clan.IsDeleted) // recreate clan { AddClanLeader(acc.AccountID, clan.ClanID, db); clan.IsDeleted = false; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("Clan {0} reformed by {1}", clan, acc)); } db.SaveChanges(); Global.Server.PublishAccountUpdate(acc); return(RedirectToAction("Detail", new { id = clan.ClanID })); } } else { return(Content("You cannot join this clan - its full, or has password, or is different faction")); } }
public ActionResult AcceptTreaty(int id) { var db = new ZkDataContext(); var treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == id); var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); if (!treaty.CanAccept(acc)) { return(Content("You do not have rights to accept treaties")); } // note: we don't actually need to make sure trade can be executed before storing guarantee, // because if either fails we just don't save the changes to database var isOneTimeOnly = treaty.TreatyEffects.All(x => x.TreatyEffectType.IsOneTimeOnly); if (treaty.ProcessTrade(true) == null && (isOneTimeOnly || treaty.StoreGuarantee())) { treaty.AcceptedAccountID = acc.AccountID; treaty.TreatyState = TreatyState.Accepted; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("Treaty {0} between {1} and {2} accepted by {3}", treaty, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID, acc)); PlanetWarsTurnHandler.SetPlanetOwners(new PlanetwarsEventCreator(), db); db.SaveChanges(); if (isOneTimeOnly) { treaty.TreatyState = TreatyState.Invalid; db.SaveChanges(); } return(RedirectToAction("Detail", new { id = Global.FactionID })); } return(Content("One or both parties are unable to meet treaty conditions")); }
public ActionResult CreateLink(int planetID, int structureTypeID, int targetID) { var db = new ZkDataContext(); PlanetStructure structure = db.PlanetStructures.FirstOrDefault(x => x.PlanetID == planetID && x.StructureTypeID == structureTypeID); Planet source = db.Planets.FirstOrDefault(x => x.PlanetID == planetID); Planet target = db.Planets.FirstOrDefault(x => x.PlanetID == targetID); // warp jammers protect against link creation //var warpDefense = target.PlanetStructures.Where(x => x.StructureType.EffectBlocksJumpgate == true).ToList(); //if (warpDefense.Count > 0) return Content("Warp jamming prevents link creation"); if (source.GalaxyID != target.GalaxyID) { return(Content("Cannot form exo-galaxy link")); } db.Links.InsertOnSubmit(new Link { PlanetID1 = source.PlanetID, PlanetID2 = target.PlanetID, GalaxyID = source.GalaxyID }); db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("A new link was created between {0} planet {1} and {2} planet {3} by the {4}", source.Faction, source, target.Faction, target, structure.StructureType)); db.SaveChanges(); return(null); }
/// <summary> /// Create or modify a PlanetWars <see cref="FactionTreaty"/> /// </summary> /// <param name="factionTreatyID">Existing <see cref="FactionTreaty"/> ID, if modifying one</param> /// <param name="turns">How long the treaty lasts</param> /// <param name="acceptingFactionID"></param> /// <param name="effectTypeID"><see cref="TreatyEffect"/> to add or remove, if applicable</param> /// <param name="effectValue"></param> /// <param name="planetID">Specifies the <see cref="Planet"/> for planet-based effects</param> /// <param name="isReverse"></param> /// <param name="note">Diplomatic note readable by both parties, to better communicate their intentions</param> /// <param name="add">If not null or empty, add the specified <see cref="TreatyEffect"/></param> /// <param name="delete">Delete the specified <see cref="TreatyEffect"/>?</param> /// <param name="propose">If not null or empty, this is a newly proposed treaty</param> /// <returns></returns> public ActionResult ModifyTreaty(int factionTreatyID, int?turns, int?acceptingFactionID, int?effectTypeID, double?effectValue, int?planetID, bool?isReverse, string note, string add, int?delete, string propose) { if (!Global.Account.HasFactionRight(x => x.RightDiplomacy)) { return(Content("Not a diplomat!")); } FactionTreaty treaty; // submit, store treaty in db var db = new ZkDataContext(); if (factionTreatyID > 0) { treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == factionTreatyID); if (treaty.TreatyState != TreatyState.Invalid) { return(Content("Treaty already in progress!")); } } else { treaty = new FactionTreaty(); db.FactionTreaties.InsertOnSubmit(treaty); treaty.FactionByAcceptingFactionID = db.Factions.Single(x => x.FactionID == acceptingFactionID); } treaty.AccountByProposingAccountID = db.Accounts.Find(Global.AccountID); treaty.FactionByProposingFactionID = db.Factions.Single(x => x.FactionID == Global.FactionID); treaty.TurnsRemaining = turns; treaty.TurnsTotal = turns; treaty.TreatyNote = note; if (!string.IsNullOrEmpty(add)) { TreatyEffectType effectType = db.TreatyEffectTypes.Single(x => x.EffectTypeID == effectTypeID); var effect = new TreatyEffect { FactionByGivingFactionID = isReverse == true ? treaty.FactionByAcceptingFactionID : treaty.FactionByProposingFactionID, FactionByReceivingFactionID = isReverse == true ? treaty.FactionByProposingFactionID : treaty.FactionByAcceptingFactionID, TreatyEffectType = effectType, FactionTreaty = treaty }; if (effectType.HasValue) { if (effectType.MinValue.HasValue && effectValue < effectType.MinValue.Value) { effectValue = effectType.MinValue; } if (effectType.MaxValue.HasValue && effectValue > effectType.MaxValue.Value) { effectValue = effectType.MaxValue; } } if (effectType.HasValue) { effect.Value = effectValue; } if (effectType.IsPlanetBased) { effect.PlanetID = planetID.Value; } db.TreatyEffects.InsertOnSubmit(effect); } if (delete != null) { db.TreatyEffects.DeleteOnSubmit(db.TreatyEffects.Single(x => x.TreatyEffectID == delete)); } db.SaveChanges(); if (!string.IsNullOrEmpty(propose)) { treaty.TreatyState = TreatyState.Proposed; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} proposes a new treaty between {1} and {2} - {3}", treaty.AccountByProposingAccountID, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID, treaty)); db.SaveChanges(); return(RedirectToAction("Detail", new { id = treaty.ProposingFactionID })); } return(View("FactionTreatyDefinition", db.FactionTreaties.Find(treaty.FactionTreatyID))); }
public ActionResult SubmitCreate(Clan clan, HttpPostedFileBase image, HttpPostedFileBase bgimage, bool noFaction = false) { //using (var scope = new TransactionScope()) //{ ZkDataContext db = new ZkDataContext(); bool created = clan.ClanID == 0; // existing clan vs creation var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); //return Content(noFaction ? "true":"false"); if (noFaction) { clan.FactionID = null; } Faction new_faction = db.Factions.SingleOrDefault(x => x.FactionID == clan.FactionID); if ((new_faction != null) && new_faction.IsDeleted) { return(Content("Cannot create clans in deleted factions")); } if (string.IsNullOrEmpty(clan.ClanName) || string.IsNullOrEmpty(clan.Shortcut)) { return(Content("Name and shortcut cannot be empty!")); } if (!ZkData.Clan.IsShortcutValid(clan.Shortcut)) { return(Content("Shortcut must have at least 1 characters and contain only numbers and letters")); } if (created && (image == null || image.ContentLength == 0)) { return(Content("A clan image is required")); } Clan orgClan = null; if (!created) { if (!Global.IsModerator && (!Global.Account.HasClanRight(x => x.RightEditTexts) || clan.ClanID != Global.Account.ClanID)) { return(Content("Unauthorized")); } // check if our name or shortcut conflicts with existing clans var existingClans = db.Clans.Where(x => ((SqlFunctions.PatIndex(clan.Shortcut, x.Shortcut) > 0 || SqlFunctions.PatIndex(clan.ClanName, x.ClanName) > 0) && x.ClanID != clan.ClanID)); if (existingClans.Count() > 0) { if (existingClans.Any(x => !x.IsDeleted)) { return(Content("Clan with this shortcut or name already exists")); } } orgClan = db.Clans.Single(x => x.ClanID == clan.ClanID); string orgImageUrl = Server.MapPath(orgClan.GetImageUrl()); string orgBGImageUrl = Server.MapPath(orgClan.GetBGImageUrl()); string orgShortcut = orgClan.Shortcut; string newImageUrl = Server.MapPath(clan.GetImageUrl()); string newBGImageUrl = Server.MapPath(clan.GetBGImageUrl()); if (Global.IsModerator && (!Global.Account.HasClanRight(x => x.RightEditTexts) || clan.ClanID != Global.Account.ClanID)) { Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, string.Format("{0} edited clan {1} {2}", Global.Account.Name, orgClan.ClanName, Url.Action("Detail", "Clans", new { id = clan.ClanID }, "http"))); if (orgClan.ClanName != clan.ClanName) { Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, string.Format("{0} => {1}", orgClan.ClanName, clan.ClanName)); } } orgClan.ClanName = clan.ClanName; orgClan.Shortcut = clan.Shortcut; orgClan.Description = clan.Description; orgClan.SecretTopic = clan.SecretTopic; orgClan.Password = clan.Password; bool shortcutChanged = orgShortcut != clan.Shortcut; if (image != null && image.ContentLength > 0) { var im = Image.FromStream(image.InputStream); if (im.Width != 64 || im.Height != 64) { im = im.GetResized(64, 64, InterpolationMode.HighQualityBicubic); } im.Save(newImageUrl); } else if (shortcutChanged) { //if (System.IO.File.Exists(newImageUrl)) System.IO.File.Delete(newImageUrl); //System.IO.File.Move(orgImageUrl, newImageUrl); try { //var im = Image.FromFile(orgImageUrl); //im.Save(newImageUrl); System.IO.File.Copy(orgImageUrl, newImageUrl, true); } catch (System.IO.FileNotFoundException fnfex) // shouldn't happen but hey { return(Content("A clan image is required")); } } if (bgimage != null && bgimage.ContentLength > 0) { var im = Image.FromStream(bgimage.InputStream); im.Save(newBGImageUrl); } else if (shortcutChanged) { //if (System.IO.File.Exists(newBGImageUrl)) System.IO.File.Delete(newBGImageUrl); //System.IO.File.Move(orgBGImageUrl, newBGImageUrl); try { //var im = Image.FromFile(orgBGImageUrl); //im.Save(newBGImageUrl); System.IO.File.Copy(orgBGImageUrl, newBGImageUrl, true); } catch (System.IO.FileNotFoundException fnfex) { // there wasn't an original background image, do nothing } } if (clan.FactionID != orgClan.FactionID) { // set factions of members Faction oldFaction = orgClan.Faction; orgClan.FactionID = clan.FactionID; foreach (Account member in orgClan.Accounts) { if (member.FactionID != clan.FactionID && member.FactionID != null) { FactionsController.PerformLeaveFaction(member.AccountID, true, db); } member.FactionID = clan.FactionID; } db.SaveChanges(); if (clan.FactionID != null) { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("Clan {0} moved to faction {1}", orgClan, orgClan.Faction)); } else { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("Clan {0} left faction {1}", orgClan, oldFaction)); } } db.SaveChanges(); } else { if (Global.Clan != null) { return(Content("You already have a clan")); } // should just change their faction for them? if (Global.FactionID != 0 && Global.FactionID != clan.FactionID) { return(Content("Clan must belong to same faction you are in")); } // check if our name or shortcut conflicts with existing clans // if so, allow us to create a new clan over it if it's a deleted clan, else block action var existingClans = db.Clans.Where(x => ((SqlFunctions.PatIndex(clan.Shortcut, x.Shortcut) > 0 || SqlFunctions.PatIndex(clan.ClanName, x.ClanName) > 0) && x.ClanID != clan.ClanID)); if (existingClans.Count() > 0) { if (existingClans.Any(x => !x.IsDeleted)) { return(Content("Clan with this shortcut or name already exists")); } Clan deadClan = existingClans.First(); Clan inputClan = clan; clan = deadClan; if (noFaction) { clan.FactionID = null; } clan.IsDeleted = false; clan.ClanName = inputClan.ClanName; clan.Password = inputClan.Password; clan.Description = inputClan.Description; clan.SecretTopic = inputClan.SecretTopic; } else { db.Clans.InsertOnSubmit(clan); } db.SaveChanges(); acc.ClanID = clan.ClanID; // we created a new clan, set self as founder and rights AddClanLeader(acc.AccountID, clan.ClanID, db); db.SaveChanges(); if (image != null && image.ContentLength > 0) { var im = Image.FromStream(image.InputStream); if (im.Width != 64 || im.Height != 64) { im = im.GetResized(64, 64, InterpolationMode.HighQualityBicubic); } im.Save(Server.MapPath(clan.GetImageUrl())); } if (bgimage != null && bgimage.ContentLength > 0) { var im = Image.FromStream(bgimage.InputStream); im.Save(Server.MapPath(clan.GetBGImageUrl())); } db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("New clan {0} formed by {1}", clan, acc)); db.SaveChanges(); } Global.Server.PublishAccountUpdate(acc); //scope.Complete(); Global.Server.ChannelManager.AddClanChannel(clan);; Global.Server.SetTopic(clan.GetClanChannel(), clan.SecretTopic, Global.Account.Name); //} return(RedirectToAction("Detail", new { id = clan.ClanID })); }
private ActionResult ChangePlanetMap(int planetID, int structureTypeID, int targetID, int?newMapID) { var db = new ZkDataContext(); PlanetStructure structure = db.PlanetStructures.FirstOrDefault(x => x.PlanetID == planetID && x.StructureTypeID == structureTypeID); Planet source = db.Planets.FirstOrDefault(x => x.PlanetID == planetID); Planet target = db.Planets.FirstOrDefault(x => x.PlanetID == targetID); Galaxy gal = db.Galaxies.FirstOrDefault(x => x.GalaxyID == source.GalaxyID); if (newMapID == null) { List <Resource> mapList = db.Resources.Where( x => x.MapPlanetWarsIcon != null && x.Planets.Where(p => p.GalaxyID == gal.GalaxyID).Count() == 0 && x.MapSupportLevel >= MapSupportLevel.Featured && x.ResourceID != source.MapResourceID).ToList(); if (mapList.Count > 0) { int r = new Random().Next(mapList.Count); newMapID = mapList[r].ResourceID; } } if (newMapID != null) { Resource newMap = db.Resources.Single(x => x.ResourceID == newMapID); target.Resource = newMap; gal.IsDirty = true; string word = ""; if (target.Faction == source.Faction) { if (target.TeamSize < GlobalConst.PlanetWarsMaxTeamsize) { target.TeamSize++; } word = "terraformed"; } else { word = "nanodegraded"; if (target.TeamSize > 1) { target.TeamSize--; } } db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} {1} has been {6} by {2} from {3} {4}. New team size is {5} vs {5}", target.Faction, target, structure.StructureType, source.Faction, source, target.TeamSize, word)); } else { return (Content(string.Format("Terraform attempt on {0} {1} using {2} from {3} {4} has failed - no valid maps", target.Faction, target, structure.StructureType, source.Faction, source))); } db.SaveChanges(); return(null); }
public ActionResult BombPlanet(int planetID, int count, bool?useWarp) { var db = new ZkDataContext(); Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); if (acc.Faction == null) { return(Content("Join some faction first")); } Planet planet = db.Planets.Single(x => x.PlanetID == planetID); bool accessible = (useWarp == true) ? planet.CanBombersWarp(acc.Faction) : planet.CanBombersAttack(acc.Faction); if (!accessible) { return(Content("You cannot attack here")); } if (Global.Server.GetPlanetBattles(planet).Any(x => x.IsInGame)) { return(Content("Battle in progress on the planet, cannot bomb planet")); } bool selfbomb = acc.FactionID == planet.OwnerFactionID; if (count < 0) { count = 0; } double avail = Math.Min(count, acc.GetBombersAvailable()); if (useWarp == true) { avail = Math.Min(acc.GetWarpAvailable(), avail); } var capa = acc.GetBomberCapacity(); if (avail > capa) { return(Content("Too many bombers - the fleet limit is " + capa)); } if (avail > 0) { double defense = planet.PlanetStructures.Where(x => x.IsActive).Sum(x => x.StructureType.EffectBomberDefense) ?? 0; double effective = avail; if (!selfbomb) { effective = effective - defense; } if (effective <= 0) { return(Content("Enemy defenses completely block your ships")); } acc.SpendBombers(avail); if (useWarp == true) { acc.SpendWarps(avail); } var r = new Random(); double strucKillChance = !selfbomb ? effective * GlobalConst.BomberKillStructureChance : 0; int strucKillCount = (int)Math.Floor(strucKillChance + r.NextDouble()); double ipKillChance = effective * GlobalConst.BomberKillIpChance; int ipKillCount = (int)Math.Floor(ipKillChance + r.NextDouble()); List <PlanetStructure> structs = planet.PlanetStructures.Where(x => x.StructureType.IsBomberDestructible).ToList(); var bombed = new List <StructureType>(); while (structs.Count > 0 && strucKillCount > 0) { strucKillCount--; PlanetStructure s = structs[r.Next(structs.Count)]; bombed.Add(s.StructureType); structs.Remove(s); db.PlanetStructures.DeleteOnSubmit(s); } double ipKillAmmount = ipKillCount * GlobalConst.BomberKillIpAmount; if (ipKillAmmount > 0) { var influenceDecayMin = planet.PlanetStructures.Where(x => x.IsActive && x.StructureType.EffectPreventInfluenceDecayBelow != null).Select(x => x.StructureType.EffectPreventInfluenceDecayBelow).OrderByDescending(x => x).FirstOrDefault() ?? 0; foreach (PlanetFaction pf in planet.PlanetFactions.Where(x => x.FactionID != acc.FactionID)) { pf.Influence -= ipKillAmmount; if (pf.Influence < 0) { pf.Influence = 0; } // prevent bombing below influence decaymin for owner - set by active structures if (pf.FactionID == planet.OwnerFactionID && pf.Influence < influenceDecayMin) { pf.Influence = influenceDecayMin; } } } var args = new List <object> { acc, acc.Faction, !selfbomb ? planet.Faction : null, planet, avail, defense, useWarp == true ? "They attacked by warp. " : "", ipKillAmmount }; args.AddRange(bombed); string str; if (selfbomb) { str = "{0} of {1} bombed own planet {3} using {4} bombers against {5} defenses. {6}Ground armies lost {7} influence"; } else { str = "{0} of {1} bombed {2} planet {3} using {4} bombers against {5} defenses. {6}Ground armies lost {7} influence"; } if (bombed.Count > 1) { str += " and "; int counter = 8; foreach (var b in bombed) { str += "{" + counter + "}" + ", "; counter++; } str += " were destroyed."; } else if (bombed.Count == 1) { str += " and {8} was destroyed."; } else { str += "."; } db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent(str, args.ToArray())); } db.SaveChanges(); PlanetWarsTurnHandler.SetPlanetOwners(new PlanetwarsEventCreator()); return(RedirectToAction("Planet", new { id = planetID })); }
public ActionResult SendDropships(int planetID, int count, bool?useWarp) { var db = new ZkDataContext(); Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID); if (acc.Faction == null) { return(Content("Join a faction first")); } Planet planet = db.Planets.SingleOrDefault(x => x.PlanetID == planetID); int there = planet.PlanetFactions.Where(x => x.FactionID == acc.FactionID).Sum(x => (int?)x.Dropships) ?? 0; bool accessible = useWarp == true?planet.CanDropshipsWarp(acc.Faction) : planet.CanDropshipsAttack(acc.Faction); if (!accessible) { return(Content(string.Format("That planet cannot be attacked"))); } if (Global.Server.GetPlanetBattles(planet).Any(x => x.IsInGame)) { return(Content("Battle in progress on the planet, cannot send ships")); } int cnt = Math.Max(count, 0); int capa = acc.GetDropshipCapacity(); if (cnt + there > capa) { return(Content("Too many dropships on planet - the fleet limit is " + capa)); } cnt = Math.Min(cnt, (int)acc.GetDropshipsAvailable()); if (useWarp == true) { cnt = Math.Min(cnt, (int)acc.GetWarpAvailable()); } if (cnt > 0) { acc.SpendDropships(cnt); if (useWarp == true) { acc.SpendWarps(cnt); if (cnt < GlobalConst.DropshipsForFullWarpIPGain) { return(Content($"You must send at least {GlobalConst.DropshipsForFullWarpIPGain} dropships when warping")); } } if (planet.Account != null) { Global.Server.GhostPm(planet.Account.Name, string.Format( "Warning: long range scanners detected fleet of {0} ships inbound to your planet {1} {3}/Planetwars/Planet/{2}", cnt, planet.Name, planet.PlanetID, GlobalConst.BaseSiteUrl)); } PlanetFaction pac = planet.PlanetFactions.SingleOrDefault(x => x.FactionID == acc.FactionID); if (pac == null) { pac = new PlanetFaction { FactionID = Global.FactionID, PlanetID = planetID }; db.PlanetFactions.InsertOnSubmit(pac); } pac.Dropships += cnt; pac.DropshipsLastAdded = DateTime.UtcNow; if (cnt > 0) { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} sends {1} {2} dropships to {3} {4} {5}", acc, cnt, acc.Faction, planet.Faction, planet, useWarp == true ? "using warp drives" : "")); } db.SaveChanges(); } return(RedirectToAction("Planet", new { id = planetID })); }
/// <summary> /// Automatically close old polls /// </summary> public static void AutoClosePolls() { var db = new ZkDataContext(); foreach (var p in db.Polls.Where(x => x.IsHeadline && x.ExpireBy != null && x.ExpireBy < DateTime.UtcNow && x.RoleTypeID != null).ToList()) { var yes = p.PollVotes.Count(x => x.PollOption.OptionText == "Yes"); var no = p.PollVotes.Count(x => x.PollOption.OptionText == "No"); var acc = p.AccountByRoleTargetAccountID; if (yes > no) { if (p.RoleIsRemoval) { var toDelete = db.AccountRoles.Where(x => x.AccountID == acc.AccountID && x.RoleTypeID == p.RoleTypeID); db.AccountRoles.DeleteAllOnSubmit(toDelete); db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} was removed from the {1} role of {2} by a vote - {3} for, {4} against", acc, (object)p.Clan ?? p.Faction, p.RoleType, yes, no)); db.SaveChanges(); Global.Server.GhostPm(acc.Name, string.Format("You were recalled from the function of {0} by a vote", p.RoleType.Name)); } else { if (!acc.AccountRolesByAccountID.Any(x => x.RoleTypeID == p.RoleTypeID)) { Account previous = null; if (p.RoleType.IsOnePersonOnly) { var entries = db.AccountRoles.Where(x => x.RoleTypeID == p.RoleTypeID && (p.RoleType.IsClanOnly ? x.ClanID == p.RestrictClanID : x.FactionID == p.RestrictFactionID)).ToList(); if (entries.Any()) { previous = entries.First().Account; db.AccountRoles.DeleteAllOnSubmit(entries); db.SaveChanges(); } } var entry = new AccountRole() { Account = acc, Inauguration = DateTime.UtcNow, Clan = p.Clan, Faction = p.Faction, RoleType = p.RoleType }; acc.AccountRolesByAccountID.Add(entry); if (previous == null) { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} was elected for the {1} role of {2} by a vote - {3} for, {4} against", acc, (object)p.Clan ?? p.Faction, p.RoleType, yes, no)); } else { db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} was elected for the {1} role of {2} by a vote, replacing {3} - {4} for, {5} against", acc, (object)p.Clan ?? p.Faction, p.RoleType, previous, yes, no)); } Global.Server.GhostPm(acc.Name, string.Format("Congratulations!! You were elected into a function of {0} by a vote", p.RoleType.Name)); } } } p.IsHeadline = false; db.Polls.DeleteOnSubmit(p); } db.SaveChanges(); }
/// <summary> /// Create or modify a PlanetWars <see cref="FactionTreaty"/> /// </summary> /// <param name="factionTreatyID">Existing <see cref="FactionTreaty"/> ID, if modifying one</param> /// <param name="turns">How long the treaty lasts</param> /// <param name="acceptingFactionID"></param> /// <param name="effectTypeID"><see cref="TreatyEffect"/> to add or remove, if applicable</param> /// <param name="effectValue"></param> /// <param name="planetID">Specifies the <see cref="Planet"/> for planet-based effects</param> /// <param name="isReverse"></param> /// <param name="note">Diplomatic note readable by both parties, to better communicate their intentions</param> /// <param name="add">If not null or empty, add the specified <see cref="TreatyEffect"/></param> /// <param name="delete">Delete the specified <see cref="TreatyEffect"/>?</param> /// <param name="propose">If not null or empty, this is a newly proposed treaty</param> /// <returns></returns> public ActionResult ModifyTreaty(int factionTreatyID, int?turns, int?acceptingFactionID, int?effectTypeID, double?effectValue, int?planetID, bool?isReverse, TreatyUnableToTradeMode?treatyUnableToTradeMode, int?proposingFactionGuarantee, int?acceptingFactionGuarantee, string note, string add, int?delete, string propose) { if (Global.Account == null) { return(Content("You must be logged in to manage treaties")); } if (!Global.Account.HasFactionRight(x => x.RightDiplomacy)) { return(Content("Not a diplomat!")); } FactionTreaty treaty; // submit, store treaty in db var db = new ZkDataContext(); if (factionTreatyID > 0) { treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == factionTreatyID); if (treaty.TreatyState != TreatyState.Invalid) { return(Content("Treaty already in progress!")); } } else { if (factionTreatyID == acceptingFactionID) { return(Content("Faction cannot enter into treaty with itself")); } treaty = new FactionTreaty(); db.FactionTreaties.InsertOnSubmit(treaty); treaty.FactionByAcceptingFactionID = db.Factions.Single(x => x.FactionID == acceptingFactionID); } treaty.AccountByProposingAccountID = db.Accounts.Find(Global.AccountID); treaty.FactionByProposingFactionID = db.Factions.Single(x => x.FactionID == Global.FactionID); treaty.TurnsRemaining = turns; treaty.TurnsTotal = turns; treaty.TreatyNote = note; treaty.TreatyUnableToTradeMode = treatyUnableToTradeMode ?? TreatyUnableToTradeMode.Cancel; treaty.ProposingFactionGuarantee = Math.Max(proposingFactionGuarantee ?? 0, 0); treaty.AcceptingFactionGuarantee = Math.Max(acceptingFactionGuarantee ?? 0, 0); if (!string.IsNullOrEmpty(add)) { TreatyEffectType effectType = db.TreatyEffectTypes.Single(x => x.EffectTypeID == effectTypeID); var effect = new TreatyEffect { FactionByGivingFactionID = isReverse == true ? treaty.FactionByAcceptingFactionID : treaty.FactionByProposingFactionID, FactionByReceivingFactionID = isReverse == true ? treaty.FactionByProposingFactionID : treaty.FactionByAcceptingFactionID, TreatyEffectType = effectType, FactionTreaty = treaty }; if (effectType.HasValue) { if (effectType.MinValue.HasValue && effectValue < effectType.MinValue.Value) { effectValue = effectType.MinValue; } if (effectType.MaxValue.HasValue && effectValue > effectType.MaxValue.Value) { effectValue = effectType.MaxValue; } } if (effectType.HasValue) { effect.Value = effectValue; } if (effectType.IsPlanetBased) { effect.PlanetID = planetID.Value; effect.Planet = db.Planets.Find(planetID.Value); if (effect.Planet.PlanetStructures.Any(x => x.StructureType.OwnerChangeWinsGame == true) && effectType.TreatyEffects.Any(x => x.TreatyEffectType.EffectGiveInfluence == true)) { return(Content("Cannot trade influence on victory planets")); } } db.TreatyEffects.InsertOnSubmit(effect); } if (delete != null) { db.TreatyEffects.DeleteOnSubmit(db.TreatyEffects.Single(x => x.TreatyEffectID == delete)); } db.SaveChanges(); if (!string.IsNullOrEmpty(propose)) { treaty.TreatyState = TreatyState.Proposed; db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} proposes a new treaty between {1} and {2} - {3}", treaty.AccountByProposingAccountID, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID, treaty)); db.SaveChanges(); return(RedirectToAction("Detail", new { id = treaty.ProposingFactionID })); } return(View("FactionTreatyDefinition", db.FactionTreaties.Find(treaty.FactionTreatyID))); }