/// <summary> /// Player constructor. /// </summary> /// <param name="color"></param> public Player(Alliance alliance, Color color, Point startLocation) { Game1.GetInstance().players.AddLast(this); this.device = Game1.GetInstance().GraphicsDevice; this.alliance = alliance; this.startLocation = startLocation; if (!this.alliance.members.Contains(this)) this.alliance.members.AddLast(this); this.color = color; selectionTex = Game1.GetInstance().Content.Load<Texture2D>("Selection"); selectedTex = Game1.GetInstance().Content.Load<Texture2D>("Selected"); units = new CustomArrayList<Unit>(); buildings = new CustomArrayList<Building>(); hud = new HUD(this, color); resources = 100000; meleeStore = new MeleeStore(this); rangedStore = new RangedStore(this); fastStore = new FastStore(this); arrowManager = new ArrowManager(); lightTexture = Game1.GetInstance().Content.Load<Texture2D>("Fog/Light"); MouseManager.GetInstance().mouseClickedListeners += ((MouseClickListener)this).OnMouseClick; MouseManager.GetInstance().mouseReleasedListeners += ((MouseClickListener)this).OnMouseRelease; MouseManager.GetInstance().mouseMotionListeners += ((MouseMotionListener)this).OnMouseMotion; MouseManager.GetInstance().mouseDragListeners += ((MouseMotionListener)this).OnMouseDrag; }
public AllianceMembershipStateInfo(AllianceMembershipState state) { _action = state.GetAction(); _requestorOrganization = state.GetRequestorOrganization(); _requestedAlliance = state.GetRequestedAlliance(); _actionDateTime = state.GetActionDateTime(); }
//-------------------------------- // 3 - Shooting from another script //-------------------------------- /// <summary> /// Create a new projectile if possible /// </summary> public void Attack(Alliance alliance) { if (CanAttack) { shootCooldown = shootingRate; // Create a new shot var shotTransform = Instantiate(shotPrefab) as Transform; // Assign position shotTransform.position = transform.position; shotTransform.rotation = transform.rotation; // The is enemy property DamageOnContact shot = shotTransform.gameObject.GetComponent<DamageOnContact>(); if (shot != null) { shot.alliance = alliance; } // Make the weapon shot always towards it MoveScript move = shotTransform.gameObject.GetComponent<MoveScript>(); if (move != null) { move.direction = this.transform.right; // towards in 2D space is the right of the sprite } } }
public static Alliance FindBy(Guid key) { Alliance allianceFound = new Alliance(); // ContentStream contentStreamFound = null; using (var db = new FHNWPrototypeDB()) { // .Include("Wall.Posts.Author.User") //.Include("Wall.Posts.Comments.Author.User") var result = (from alliance in db.Alliances //.Include("AllianceMemberships.AllianceRequested") .Include("AllianceMemberships.OrganizationRequestor") //.Include("Wall.Posts.Author") //.Include("Wall.Posts.Comments.Author") where alliance.Key == key select alliance).FirstOrDefault(); //contentStreamFound = (from cs in db.ContentStreams // .Include("Posts.Author") // .Include("Posts.PostLikes") // .Include("Posts.Comments.Author") // .Include("Posts.Comments.CommentLikes") // where cs.Owner.ReferenceKey == allianceFound.Key // select cs).FirstOrDefault(); //if (contentStreamFound != null) //{ // var newPostList = contentStreamFound.Posts.OrderByDescending(x => x.PublishDateTime).ToList(); // foreach (var post in newPostList) // { // var newCommentList = post.Comments.OrderBy(x => x.PublishDateTime).ToList(); // post.Comments = newCommentList; // } // contentStreamFound.Posts = newPostList; //} //else //{ // contentStreamFound = new ContentStream(); // contentStreamFound.Posts = new List<Post>(); //} // allianceFound.Wall = contentStreamFound; allianceFound.Key = result.Key; allianceFound.Name = result.Name; allianceFound.Description = result.Description; allianceFound.AllianceMemberships = result.AllianceMemberships; return allianceFound; } }
protected void btnFound_Click(object sender, EventArgs e) { if (IsValid) { Alliance a = new Alliance(txtFound.Text); a.Image = Configuration.Default_Gfx_Path+"/Portal/Logo.gif"; a.Description = "no description given."; a.Directive = "no directive given."; a.LongName = a.Name; player.Alliance = a; player.IsAccepted = true; player.Vote = player; Response.Redirect("Alliance.aspx"); } else Wc3o.Game.Message(Master, "Your data is not valid.", MessageType.Error); }
public Bot(teleAbility kind, autoAbility autoKind, Alliance side) { canShoot = kind.HasFlag(teleAbility.shoot); canClimb = kind.HasFlag(teleAbility.climb); canBreach = kind.HasFlag(teleAbility.breach); canAuto = autoKind; hasBall = true; //let each robot start with a ball mode = botMode.none; strategy = new BotStrategy(this); location.current = fieldLocation.places.neutral; destination = fieldLocation.places.not_set; distancetogo = 0; team = side; maxSpeed = 5.0; //default to 5 fps }
bool IsAbilityTargetMatch(PlanOfAttack poa, Tile tile) { bool isMatch = false; if (poa.target == Targets.Tile) { isMatch = true; } else if (poa.target != Targets.None) { Alliance other = tile.content.GetComponentInChildren <Alliance>(); if (other != null && alliance.IsMatch(other, poa.target)) { isMatch = true; } } return(isMatch); }
public static Alliance CreateAlliance(long seed) { object vDatabaseLock = ObjectManager.m_vDatabaseLock; Alliance alliance; lock (vDatabaseLock) { if (seed == 0L) { seed = ObjectManager.m_vAllianceSeed; } alliance = new Alliance(seed); ObjectManager.m_vAllianceSeed += 1L; } ObjectManager.m_vDatabase.CreateAlliance(alliance); ObjectManager.m_vAlliances.Add(alliance.GetAllianceId(), alliance); return(alliance); }
private void addNPCAlliances(Dictionary <int, GraphicModel.SolarSystem> solarSystems) { var npcs = DAL.GetNpcInfs(); Color npcclolr = Color.FromArgb(0, 0, 0, 0); foreach (var npcInf in npcs) { var alliance = new Alliance() { id = npcInf.npcid, name = npcInf.name, colorString = "000000", isNPC = true }; this.alliances[npcInf.npcid] = alliance; addInfluence(solarSystems[npcInf.systemid], npcInf.inf, alliance, 4, new List <GraphicModel.SolarSystem>()); } }
/// <summary> /// Creates or gets a alliance. /// </summary> /// <param name="id">Alliance id.</param> /// <returns>Created or found alliance.</returns> public Alliance CreateAlliance(int id) { if (Alliances.ContainsKey(id)) { return(Alliances[id]); } var a = new Alliance(id); Alliances.Add(id, a); if (OnNewAlliance != null) { OnNewAlliance.Invoke(a); } return(a); }
//adds an airline facility to the airport public void addAirlineFacility(AirportFacility facility) { AirlineAirportFacility nextFacility = new AirlineAirportFacility(GameObject.GetInstance().HumanAirline, this.Airport, facility, GameObject.GetInstance().GameTime.AddDays(facility.BuildingDays)); this.Airport.setAirportFacility(nextFacility); AirlineAirportFacilityMVVM currentFacility = this.AirlineFacilities.Where(f => f.Facility.Facility.Type == facility.Type).FirstOrDefault(); if (currentFacility != null) { this.AirlineFacilities.Remove(currentFacility); } Alliance alliance = nextFacility.Airline.Alliances.Count == 0 ? null : nextFacility.Airline.Alliances[0]; this.AirlineFacilities.Add(new AirlineAirportFacilityMVVM(nextFacility, alliance)); }
public void AddCharacterToArena(ICharacter c, Alliance alliance, int? xLoc = null, int? yLoc = null) { if (ArenaFloor == null) { throw new Exception("Arena not been constructed!"); } c.ChangeAlliance(alliance); Characters.Add(c); if (xLoc == null || yLoc == null) { SetDefaultCharacterLocation(c); } else { ArenaFloor[(int)xLoc, (int)yLoc].AddEntityToTile((Character)c); } }
/// <summary> /// This function get the info of an alliance. /// </summary> /// <param name="allianceId">The (Int64) ID of the alliance.</param> /// <returns>Return data about the alliance.</returns> public static Alliance GetAlliance(long allianceId) { Alliance alliance = null; if (m_vAlliances.ContainsKey(allianceId)) { alliance = m_vAlliances[allianceId]; } else { alliance = m_vDatabase.GetAlliance(allianceId); if (alliance != null) { m_vAlliances.Add(alliance.GetAllianceId(), alliance); } } return(alliance); }
/// <summary> /// Player constructor. /// </summary> /// <param name="color"></param> public Player(Alliance alliance, Color color) { this.alliance = alliance; if (!this.alliance.members.Contains(this)) this.alliance.members.AddLast(this); this.color = color; selectionTex = Game1.GetInstance().Content.Load<Texture2D>("Selection"); selectedTex = Game1.GetInstance().Content.Load<Texture2D>("Selected"); units = new LinkedList<Unit>(); buildings = new LinkedList<Building>(); hud = new HUD(this, color); MouseManager.GetInstance().mouseClickedListeners += ((MouseClickListener)this).OnMouseClick; MouseManager.GetInstance().mouseReleasedListeners += ((MouseClickListener)this).OnMouseRelease; MouseManager.GetInstance().mouseMotionListeners += ((MouseMotionListener)this).OnMouseMotion; MouseManager.GetInstance().mouseDragListeners += ((MouseMotionListener)this).OnMouseDrag; }
/// <summary> /// Deserializes the specified entity. /// </summary> public bool Deserialize(out Alliance alliance) { if (this.Profile != null) { alliance = JsonConvert.DeserializeObject <Alliance>(this.Profile.ToJson(), AllianceDb.JsonSettings); if (alliance != null) { return(true); } } else { alliance = null; } return(false); }
public HangarLog GetHangarLog(Alliance alliance) { if (!Directory.Exists(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId)) { Directory.CreateDirectory(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//"); } if (!File.Exists(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//log.json")) { HangarLog log = new HangarLog { allianceId = alliance.AllianceId }; utils.WriteToJsonFile <HangarLog>(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//log.json", log); return(log); } return(utils.ReadFromJsonFile <HangarLog>(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//log.json")); }
public void BankLog(string timeformat = "MM-dd-yyyy") { if (Context.Player != null) { //Do stuff with taking components from grid storage //GridCosts localGridCosts = GetComponentsAndCost(projectedGrid); //gridCosts.setComponents(localGridCosts.getComponents()); IMyFaction faction = FacUtils.GetPlayersFaction(Context.Player.IdentityId); if (faction == null) { Context.Respond("You must be in a faction to use alliance features."); return; } Alliance alliance = AlliancePlugin.GetAlliance(faction as MyFaction); if (alliance == null) { Context.Respond("You are not a member of an alliance with an unlocked shipyard."); return; } if (AlliancePlugin.HasFailedUpkeep(alliance)) { Context.Respond("Alliance failed to pay upkeep. Upgrades disabled."); return; } if (alliance.hasUnlockedHangar) { HangarData data = alliance.LoadHangar(); HangarLog log = data.GetHangarLog(alliance); StringBuilder sb = new StringBuilder(); log.log.Reverse(); foreach (HangarLogItem item in log.log) { sb.AppendLine(item.time.ToString(timeformat) + " : " + AlliancePlugin.GetPlayerName(item.steamid) + " " + item.action + " " + item.GridName.Split('_')[0]); continue; } DialogMessage m = new DialogMessage("Alliance Hangar Records", alliance.name, sb.ToString()); ModCommunication.SendMessageTo(m, Context.Player.SteamUserId); } else { Context.Respond("Alliance has not unlocked hangar."); } } }
public async Task <AllianceDto> Handle(CreateAllianceCommand request, CancellationToken cancellationToken) { var user = await _currentUserService.GetCurrentUser(); var entity = new Alliance { Title = request.Title, Description = request.Description, LeaderId = _currentUserService.UserId, CreationDate = DateTime.Now, Members = { user } }; await _context.Alliances.AddAsync(entity, cancellationToken); await _context.SaveChangesAsync(cancellationToken); return(_mapper.Map <AllianceDto>(entity)); }
/// <summary> /// Removes the specified alliance. /// </summary> internal static void Remove(Alliance alliance) { if (Alliances.Pool.ContainsKey(alliance.Identifier)) { if (!Alliances.Pool.TryRemove(alliance.Identifier, out Alliance tmpAlliance)) { Debugger.Error("Unsuccessfully removed the specified alliance from the dictionary."); } else { if (!tmpAlliance.Equals(alliance)) { Debugger.Error("Successfully removed a alliance from the list but the returned alliance was not equal to our alliance."); } } } Alliances.Save(alliance); }
public AllianceMVVM(Alliance alliance) { this.Alliance = alliance; this.Members = new ObservableCollection <AllianceMemberMVVM>(); this.PendingMembers = new ObservableCollection <PendingAllianceMember>(); this.AllianceRoutes = new List <AllianceRouteMMVM>(); foreach (AllianceMember member in this.Alliance.Members) { this.Members.Add(new AllianceMemberMVVM(member, this.Alliance.IsHumanAlliance)); } foreach (PendingAllianceMember member in this.Alliance.PendingMembers) { this.PendingMembers.Add(member); } setValues(); }
public void FormAlliances_ShouldReturnNull_WhenMagesAreNotInMagesWithNoAlliances() { var mage1 = new Mage { Id = 1 }; var mage2 = new Mage { Id = 2 }; var mage3 = new Mage { Id = 3 }; var alliance = new Alliance(mage1, mage2); gw.MagesWithNoAlliances.Add(mage2); gw.MagesWithNoAlliances.Add(mage3); Assert.Throws <ArgumentException>(() => gw.FormAlliance(alliance)); }
static public Transform GetContainer(Card card, bool isAlly, int ContainerIndex) { Transform container; if (isAlly) { container = card.Allegiance.GetChild(ContainerIndex); } else if (card.Allegiance == Alliance) { container = Horde.GetChild(ContainerIndex); } else { container = Alliance.GetChild(ContainerIndex); } return(container); }
public void Display(GameObject obj) { Alliance alliance = obj.GetComponent <Alliance>(); background.sprite = alliance.type == Alliances.Enemy ? enemyBackground : allyBackground; avatar.sprite = obj.GetComponentInChildren <Race>().avatar; nameLabel.text = obj.name; Stats stats = obj.GetComponent <Stats>(); if (stats) { hpLabel.text = string.Format("HP {0} / {1}", stats[StatTypes.HP], stats[StatTypes.MHP]); mpLabel.text = string.Format("MP {0} / {1}", stats[StatTypes.MP], stats[StatTypes.MMP]); gpLabel.text = string.Format("GR {0} / {1}", stats[StatTypes.GP], stats[StatTypes.MGP]); lvLabel.text = string.Format("LV. {0}", stats[StatTypes.LVL]); joLabel.text = string.Format("{0}", obj.GetComponentInChildren <PerkCatalog>().transform.GetChild(0).name.First().ToString().ToUpper() + obj.GetComponentInChildren <PerkCatalog>().transform.GetChild(0).name.Substring(1).ToLower()); raLabel.text = string.Format("{0}", obj.GetComponentInChildren <Race>().raceName); } }
public static DamageActionParameter FromString(string param) { if (string.IsNullOrWhiteSpace(param)) { return(new DamageActionParameter()); } var parameters = param.Split('|'); var damageAmount = int.Parse(parameters[0]); var alliance = parameters.Length > 1 ? (Alliance)Enum.Parse(typeof(Alliance), parameters[1]) : Alliance.Enemy; return(new DamageActionParameter { DamageAmount = damageAmount, WhichPlayer = alliance == default ? Alliance.Enemy : alliance });
public override async void Execute(Level level) { try { Alliance a = await ObjectManager.GetAlliance(level.GetPlayerAvatar().GetAllianceId()); if (a != null) { AllianceMemberEntry _AllianceMemberEntry = a.GetAllianceMember(level.GetPlayerAvatar().GetId()); _AllianceMemberEntry.ToggleStatus(); PlayerWarStatusMessage _PlayerWarStatusMessage = new PlayerWarStatusMessage(level.GetClient()); _PlayerWarStatusMessage.SetStatus(_AllianceMemberEntry.GetStatus()); PacketProcessor.Send(_PlayerWarStatusMessage); } } catch (Exception) { } }
public PrintLog GetLog(Alliance alliance) { FileUtils utils = new FileUtils(); if (!Directory.Exists(AlliancePlugin.path + "//ShipyardData//" + alliance.AllianceId)) { Directory.CreateDirectory(AlliancePlugin.path + "//ShipyardData//" + alliance.AllianceId); } if (!File.Exists(AlliancePlugin.path + "//ShipyardData//" + alliance.AllianceId + "//log.json")) { PrintLog log = new PrintLog { allianceId = alliance.AllianceId }; utils.WriteToJsonFile <PrintLog>(AlliancePlugin.path + "//ShipyardData//" + alliance.AllianceId + "//log.json", log); return(log); } return(utils.ReadFromJsonFile <PrintLog>(AlliancePlugin.path + "//ShipyardData//" + alliance.AllianceId + "//log.json")); }
/// <summary> /// get the opposite direction of the current alliance for the pawns /// </summary> /// <param name="alliance"></param> /// <returns></returns> public static int getOppositeDirection(this Alliance alliance) { int direction; switch (alliance) { case Alliance.WHITE: direction = 1; break; case Alliance.BLACK: direction = -1; break; default: direction = 0; break; } return(direction); }
public bool IsMatch(Alliance other, Targets targets) { bool isMatch = false; switch (targets) { case Targets.Self: isMatch = other == this; break; case Targets.Ally: isMatch = type == other.type; break; case Targets.Foe: isMatch = (type != other.type) && other.type != Alliances.Neutral; break; } return(confused ? !isMatch : isMatch); }
public int MarkTilesForDeploy(Alliance all, bool sel, bool ignoreShips) { int returnValue = 0; if (!AllianceHasCube(all)) { return(0); } for (int i = 0; i < 4; i++) { if (tileList[ORBITAL_TILES[i]].occupyingShip == null || ignoreShips) { tileList[ORBITAL_TILES[i]].Selected = sel; returnValue++; } } return(returnValue); }
/// <summary> /// Saves the specified alliance in the specified database. /// </summary> internal static void Save(Alliance alliance, DBMS database = Settings.Database) { if (alliance != null) { switch (database) { case DBMS.Mongo: { AllianceDb.Save(alliance).GetAwaiter().GetResult(); break; } case DBMS.File: { new FileInfo($"{Directory.GetCurrentDirectory()}/Saves/Alliances/{alliance}.json").WriteAllText(JsonConvert.SerializeObject(alliance, AllianceDb.JsonSettings)); break; } } } }
public void CreateAlliance(Alliance a) { try { using (ucsdbEntities ucsdbEntities = new ucsdbEntities(this.m_vConnectionString)) { ucsdbEntities.clan.Add(new clan { ClanId = a.GetAllianceId(), LastUpdateTime = DateTime.Now, Data = a.SaveToJSON() }); ucsdbEntities.SaveChanges(); } } catch (Exception ex) { Debugger.WriteLine("[CRS] An exception occured during CreateAlliance processing :", ex, 4); } }
public static Unit GetUnit(uint unitType, Alliance alliance = Alliance.Self, bool onlyCompleted = false, bool onlyVisible = false) { foreach (var unit in ObservableUnits.Values) { if (unitType == unit.UnitType && unit.Alliance == alliance) { if (onlyCompleted && unit.BuildProgress < 1) { continue; } if (onlyVisible && (!unit.IsVisible)) { continue; } return(unit); } } return(null); }
/// <summary> /// Retrieves information about an alliance. /// </summary> /// <param name="id">The alliance ID.</param> /// <returns>The alliance with its name, or a default alliance object if none could be /// found.</returns> public Alliance GetAlliance(int id) { Alliance all; var entity = GetEntity(id); if (entity == null) { all = new Alliance(id, Constants.UNKNOWN_TEXT); QueueIDToName(id); } else { all = new Alliance(id, entity.Name); if (entity.LastUpdate < DateTime.UtcNow - refreshInterval) { QueueIDToName(id); } } return(all); }
public PartialTurnTracker AddPartialTurn(PartialTurn partialTurn) { Alliance alliance = partialTurn.Player.Alliance; if (turns.Count > 0) { if (alliance == Alliance.White) { turns.Add(new Turn(turns.Count + 1, partialTurn)); } else if (alliance == Alliance.Black) { turns[turns.Count - 1].BlackTurn = partialTurn; } } else if (turns.Count == 0) { if (alliance == Alliance.White) { FirstWhiteTurn = partialTurn; } else if (alliance == Alliance.Black) { turns.Add(new Turn(turns.Count + 1, FirstWhiteTurn, partialTurn)); } } OnPartialTurnAdded(partialTurn); Player PlayerForNextPartialTurn = null; if (partialTurn.Player == WhitePlayer) { PlayerForNextPartialTurn = BlackPlayer; } else if (partialTurn.Player == BlackPlayer) { PlayerForNextPartialTurn = WhitePlayer; } return(new PartialTurnTracker(PlayerForNextPartialTurn, ClockManager.GetCurrentClock(), Board.CurrentState)); }
public void inviteToTest() { var User1 = Mock.MockUser(id: (int)instance.identities.allianceId.getNext()); instance.users.TryAdd(User1.id, User1); var User2 = Mock.MockUser(id: (int)instance.identities.allianceId.getNext()); instance.users.TryAdd(User2.id, User2); var User3 = Mock.MockUser(id: (int)instance.identities.allianceId.getNext()); instance.users.TryAdd(User3.id, User3); Alliance.createAlliance(User1, "a1"); var Alliance1 = instance.alliances[User1.allianceId]; Alliance.createAlliance(User3, "a2"); var Alliance2 = instance.alliances[User3.allianceId]; //invite first player Alliance.inviteTo(User1, User2); Assert.AreEqual(1, instance.invitesPerAlliance[Alliance1.id].Count); Assert.AreEqual(1, instance.invitesPerUser[User2.id].Count); Assert.AreEqual(User2.id, instance.invitesPerAlliance[Alliance1.id][0]); Assert.AreEqual(Alliance1.id, instance.invitesPerUser[User2.id][0]); //invite first player again Alliance.inviteTo(User1, User2); Assert.AreEqual(1, instance.invitesPerAlliance[Alliance1.id].Count); Assert.AreEqual(1, instance.invitesPerUser[User2.id].Count); Assert.AreEqual(User2.id, instance.invitesPerAlliance[Alliance1.id][0]); Assert.AreEqual(Alliance1.id, instance.invitesPerUser[User2.id][0]); //invote second player Alliance.inviteTo(User1, User3); Assert.AreEqual(2, instance.invitesPerAlliance[Alliance1.id].Count); Assert.AreEqual(1, instance.invitesPerUser[User3.id].Count); Assert.AreEqual(User3.id, instance.invitesPerAlliance[Alliance1.id][1]); Assert.AreEqual(Alliance1.id, instance.invitesPerUser[User3.id][0]); }
public Boolean SaveGridToHangar(String gridName, ulong steamid, Alliance alliance, Vector3D position, MyFaction faction, List <MyCubeGrid> gridsToSave, long IdentityId) { if (!CheckGrids(position, IdentityId)) { AlliancePlugin.Log.Info("Failed grid check"); return(false); } if (!CheckCharacters(position, IdentityId)) { AlliancePlugin.Log.Info("Failed character check"); return(false); } HangarLog log = GetHangarLog(alliance); HangarLogItem item = new HangarLogItem(); item.action = "Saved"; item.steamid = steamid; item.GridName = gridName; item.time = DateTime.Now; log.log.Add(item); utils.WriteToJsonFile <HangarLog>(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//log.json", log); HangarItem hangItem = new HangarItem(); hangItem.name = gridName; hangItem.steamid = steamid; hangItem.position = position; ItemsInHangar.Add(getAvailableSlot(), hangItem); GridManager.SaveGridNoDelete(System.IO.Path.Combine(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//" + gridName + ".xml"), gridName, true, false, gridsToSave); if (AlliancePlugin.GridBackupInstalled) { List <MyObjectBuilder_CubeGrid> obBuilders = new List <MyObjectBuilder_CubeGrid>(); foreach (MyCubeGrid grid in gridsToSave) { obBuilders.Add(grid.GetObjectBuilder() as MyObjectBuilder_CubeGrid); } AlliancePlugin.BackupGridMethod(obBuilders, IdentityId); } utils.WriteToJsonFile <HangarData>(AlliancePlugin.path + "//HangarData//" + alliance.AllianceId + "//hangar.json", this); return(true); }
private static void FindNewLeader(Alliance alliance, AllianceMember member) { LogicClientAvatar avatar = Avatars.Get(member.Identifier); AllianceMember newLeader = alliance.Members.Find(member => member.Role == (int)Alliance.Role.CoLeader); const Alliance.Role newRole = Alliance.Role.Leader; if (newLeader != null) { newLeader.Role = (int)newRole; } else { newLeader = alliance.Members.Find(member => member.Role == (int)Alliance.Role.Admin); if (newLeader != null) { newLeader.Role = (int)newRole; } else { newLeader = alliance.Members[Loader.Random.Rand(alliance.Members.Count)]; if (newLeader != null) { newLeader.Role = (int)newRole; } } } alliance.AddEntry(new StreamEntry(member, member, StreamEntry.StreamEvent.Demoted)); alliance.AddEntry(new StreamEntry(newLeader, member, StreamEntry.StreamEvent.Promoted)); avatar.Save(); Avatars.Get(newLeader.Identifier).Save(); new AvailableServerCommandMessage(avatar.Connection, new LogicChangeAllianceRoleCommand(avatar.Connection) { Role = newRole }).Send(); }
public void BreakAlliance_ShouldIncreaseNumberOfMagesWithNoAlliancesByTwo_WhenAllianceExists() { var mage1 = new Mage { Id = 1 }; var mage2 = new Mage { Id = 2 }; var mage3 = new Mage { Id = 3 }; var mage4 = new Mage { Id = 4 }; var alliance1 = new Alliance(mage1, mage2); var alliance2 = new Alliance(mage3, mage4); gw.Alliances.Add(alliance1); gw.Alliances.Add(alliance2); var mage5 = new Mage { Id = 5 }; var mage6 = new Mage { Id = 6 }; gw.MagesWithNoAlliances.Add(mage5); gw.MagesWithNoAlliances.Add(mage6); var initialCount = gw.MagesWithNoAlliances.Count; gw.BreakAlliance(alliance2); var finalCount = gw.MagesWithNoAlliances.Count; Assert.IsTrue(finalCount == (initialCount + 2), "The mages who broke their alliance must be added to the MagesWithNoAlliances list!"); }
public void ChangeAlliance(Alliance a) { _alliance = a; }
/// <summary> /// Метод задания стороны Юниту /// </summary> /// <param name="team">Номер стороны к которой принадлежит</param> /// <param name="country">Страна принадлежности</param> /// <param name="alliance">Союз, в который входит страна</param> public void SetSide(int team, Countries country, Alliance alliance) { base.side = new Team(team, country, alliance); }
public void StartTurn(Alliance alliance) { //TODO: Add buffs to player, apply ticks to player. CurrentBattleDetails.Participants.ForEach(p => { if (p.Character.Health < (p.Character.BaseHealth + p.Character.BonusHealth)) { p.Character.GainHealth(p.Character.BaseHealthRegeneration + p.Character.BonusHealthRegeneration); } }); if (CurrentBattleDetails.BattleMode == BattleMode.ComputerVsComputer || (CurrentBattleDetails.BattleTurn != Player.GetAlliance())) { PerformAITurn(); } }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here drawLineTexture = this.Content.Load<Texture2D>("Misc/solid"); font = Content.Load<SpriteFont>("Fonts/Arial"); (collision = new RTSCollisionMap(this, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight)).PlaceNodesAroundEdges(); graphics.PreferMultiSampling = true; (quadTree = new QuadRoot(new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight) )).CreateTree(5); players = new LinkedList<Player>(); Alliance redAlliance = new Alliance(); Player humanPlayer = new Player(redAlliance, Color.Red); players.AddLast((CURRENT_PLAYER = humanPlayer)); humanPlayer.SpawnStartUnits(new Point((int)Game1.GetInstance().graphics.PreferredBackBufferWidth / 2, (int)Game1.GetInstance().graphics.PreferredBackBufferWidth / 2)); Alliance greenAlliance = new Alliance(); Player aiPlayer = new Player(greenAlliance, Color.Green); players.AddLast(aiPlayer); aiPlayer.SpawnStartUnits(new Point((int)Game1.GetInstance().graphics.PreferredBackBufferWidth / 2, 200)); //SaveManager.GetInstance().SaveNodes("C:\\Users\\Wouter\\Desktop\\test.xml"); MouseManager.GetInstance().mouseClickedListeners += ((MouseClickListener)this).OnMouseClick; MouseManager.GetInstance().mouseReleasedListeners += ((MouseClickListener)this).OnMouseRelease; MouseManager.GetInstance().mouseMotionListeners += ((MouseMotionListener)this).OnMouseMotion; MouseManager.GetInstance().mouseDragListeners += ((MouseMotionListener)this).OnMouseDrag; /*XNAPanel panel = new XNAPanel(null, new Rectangle( this.graphics.PreferredBackBufferWidth / 2 - 200, this.graphics.PreferredBackBufferHeight / 2 - 200, 400, 400)); XNAButton button = new XNAButton(panel, new Rectangle(10, 10, 100, 40), "");*/ base.Initialize(); }
public void EndBattle(Alliance winningTeam) { CurrentBattleDetails.WinningTeam = winningTeam; CurrentBattleDetails.WinnerName = CurrentBattleDetails.Participants.First(p => p.Character.GetAlliance() == winningTeam).Character.Name; CurrentBattleDetails.LoserName = CurrentBattleDetails.Participants.First(p => p.Character.GetAlliance() != winningTeam).Character.Name; CurrentBattleDetails.BattleStatus = BattleStatus.BattleOver; if (CurrentBattleDetails.BattleMode == BattleMode.ComputerVsComputer) { ProcessBattleOver(); } }
/// <summary> /// Forms a match from recorded data /// </summary> /// <param name="frc">Event to load additional data from</param> /// <param name="redData">Group of recordings from red's data</param> /// <param name="blueData">Group of recordings from blue's data</param> /// <returns></returns> public static Match FormMatch(FrcEvent frc, AllianceGroup<RecordedMatch> redData, AllianceGroup<RecordedMatch> blueData) { // Team data count (reliability) int redTeamsCount = redData.Count((rec) => rec != null); int blueTeamsCount = blueData.Count((rec) => rec != null); if (redTeamsCount + blueTeamsCount < 3 || redTeamsCount == 0 || blueTeamsCount == 0) // not enough data { return null; // Give up } Alliance red = new Alliance(redData.A.TrackedTeam, redData.B.TrackedTeam, redData.C.TrackedTeam); Alliance blue = new Alliance(blueData.A.TrackedTeam, blueData.B.TrackedTeam, blueData.C.TrackedTeam); List<RecordedMatch> allData = new List<RecordedMatch>(); foreach (RecordedMatch rec in redData) { allData.Add(rec); } foreach (RecordedMatch rec in blueData) { allData.Add(rec); } // MATCH ID (quadruple lambda!) int matchID = allData.ConvertAll<int>((rec) => rec.MatchNumber).Mode((modes) => { try { return modes.First((n) => { return !(frc.Matches.Exists((m) => m.Number == n && !m.Pregame)); }); } catch (InvalidOperationException) { Util.DebugLog(LogLevel.Warning, "SYNC", "Completed match with this ID is already present in event"); return modes.First(); } }); Match result = new Match(matchID, blue, red); result.Pregame = false; // This section is because Unprocessed and Landfill Litter type goals are shared, but // come more than one per match. double dRedLfLitter = redData.ToList().ConvertAll<int>((rec) => rec.ScoredGoals.Count( (g) => g.Type == GoalType.LandfillLitter)).Mean(); int nRedLfLitter = (int)dRedLfLitter; double dRedUnpLitter = redData.ToList().ConvertAll<int>((rec) => rec.ScoredGoals.Count( (g) => g.Type == GoalType.UnprocessedLitter)).Mean(); int nRedUnpLitter = (int)dRedUnpLitter; double dBlueLfLitter = blueData.ToList().ConvertAll<int>((rec) => rec.ScoredGoals.Count( (g) => g.Type == GoalType.UnprocessedLitter)).Mean(); int nBlueLfLitter = (int)dBlueLfLitter; double dBlueUnpLitter = blueData.ToList().ConvertAll<int>((rec) => rec.ScoredGoals.Count( (g) => g.Type == GoalType.UnprocessedLitter)).Mean(); int nBlueUnpLitter = (int)dBlueUnpLitter; // GOALS LIST List<Goal> goals = new List<Goal>(); goals.Sort((g1, g2) => g1.TimeScoredInt - g2.TimeScoredInt); foreach (RecordedMatch rec in allData) { foreach (Goal addedGoal in rec.ScoredGoals) { #region add by goal type switch (addedGoal.Type) { #region RobotSet case GoalType.RobotSet: bool alreadyHasRobotSet = goals.Exists((g) => { return g.Type == GoalType.RobotSet && g.ScoringAlliance == addedGoal.ScoringAlliance; }); if (!alreadyHasRobotSet) { goals.Add(addedGoal); } break; #endregion #region YellowToteSet case GoalType.YellowToteSet: bool alreadyHasYTS = goals.Exists((g) => { return g.Type == GoalType.YellowToteSet && g.ScoringAlliance == addedGoal.ScoringAlliance; }); if (!alreadyHasYTS) { goals.Add(addedGoal); } break; #endregion #region ContainerSet case GoalType.ContainerSet: bool alreadyHasContainerSet = goals.Exists((g) => { return g.Type == GoalType.ContainerSet && g.ScoringAlliance == addedGoal.ScoringAlliance; }); if (!alreadyHasContainerSet) { goals.Add(addedGoal); } break; #endregion #region Coopertition case GoalType.Coopertition: bool alreadyHasCoopertition = goals.Exists((g) => { return g.Type == GoalType.Coopertition; }); if (!alreadyHasCoopertition) { goals.Add(addedGoal); } break; #endregion case GoalType.GrayTote: goals.Add(addedGoal); break; case GoalType.ContainerTeleop: goals.Add(addedGoal); break; case GoalType.RecycledLitter: goals.Add(addedGoal); break; default: break; } #endregion } } for (int i = 0; i < nRedLfLitter; i++) { goals.Add(Goal.MakeLandfillLitter(AllianceColor.Red)); } for (int i = 0; i < nRedUnpLitter; i++) { goals.Add(Goal.MakeUnprocessedLitter(AllianceColor.Red)); } for (int i = 0; i < nBlueLfLitter; i++) { goals.Add(Goal.MakeLandfillLitter(AllianceColor.Blue)); } for (int i = 0; i < nBlueUnpLitter; i++) { goals.Add(Goal.MakeUnprocessedLitter(AllianceColor.Blue)); } result.Goals = goals; // PENALTIES List<Penalty> penalties = new List<Penalty>(); foreach (RecordedMatch rec in allData) { foreach (Penalty pen in rec.AlliancePenalties) { bool nearbyPenalty = penalties.Exists((p) => { return Math.Abs(p.TimeOfPenaltyInt - pen.TimeOfPenaltyInt) < PENALTY_THRESHOLD; }); if (!nearbyPenalty) { penalties.Add(pen); } } } result.Penalties = penalties; List<Goal> redGoals = result.RedGoals; int redGoalScore = redGoals.Aggregate(0, (total, g) => total + g.PointValue()); redGoalScore = result.RedPenalties.Aggregate(redGoalScore, (total, p) => total + p.ScoreChange()); List<Goal> blueGoals = result.BlueGoals; int blueGoalScore = blueGoals.Aggregate(0, (total, g) => total + g.PointValue()); blueGoalScore = result.BluePenalties.Aggregate(blueGoalScore, (total, p) => total + p.ScoreChange()); // WINNER List<AllianceColor> winnerRecords = allData.ConvertAll<AllianceColor>((rec) => rec.Winner); AllianceColor winner = winnerRecords.Mode((modes) => redGoalScore > blueGoalScore ? AllianceColor.Red : AllianceColor.Blue); // Incredibly unlikely result.Winner = winner; // WORKING result.RedWorking = new AllianceGroup<bool>(); result.RedWorking.A = redData.A != null ? redData.A.Working : true; result.RedWorking.B = redData.B != null ? redData.B.Working : true; result.RedWorking.C = redData.C != null ? redData.C.Working : true; result.BlueWorking = new AllianceGroup<bool>(); result.BlueWorking.A = blueData.A != null ? blueData.A.Working : true; result.BlueWorking.B = blueData.B != null ? blueData.B.Working : true; result.BlueWorking.C = blueData.C != null ? blueData.C.Working : true; // DEFENSE result.RedDefense = new AllianceGroup<int>(); result.RedDefense.A = redData.A != null ? redData.A.Defense : 5; result.RedDefense.B = redData.B != null ? redData.B.Defense : 5; result.RedDefense.C = redData.C != null ? redData.C.Defense : 5; result.BlueDefense = new AllianceGroup<int>(); result.BlueDefense.A = blueData.A != null ? blueData.A.Defense : 5; result.BlueDefense.B = blueData.B != null ? blueData.B.Defense : 5; result.BlueDefense.C = blueData.C != null ? blueData.C.Defense : 5; // DISCREPANCY POINTS int finalScoreRed = (int)redData.ToList().ConvertAll<int>((rec) => rec.AllianceFinalScore).Mean(); int finalScoreBlue = (int)blueData.ToList().ConvertAll<int>((rec) => rec.AllianceFinalScore).Mean(); // round down result.RedFinalScore = finalScoreRed; result.BlueFinalScore = finalScoreBlue; int dpRed = finalScoreRed - redGoalScore; int dpBlue = finalScoreBlue - blueGoalScore; result.RedDiscrepancyPoints = dpRed; result.BlueDiscrepancyPoints = dpBlue; return result; }
public static void Add(Alliance entity) { throw new NotImplementedException(); }
public override bool CanRequestAllianceMembershipRequestTo(Alliance allianceToRequest) { //check conditions _requestedAlliance = allianceToRequest; return true; }
/// <summary> /// method to handle the aliance invite /// </summary> /// <param name="player"></param> /// <param name="reponse"></param> protected void AllianceInvite(GamePlayer player, byte reponse) { if (reponse != 0x01) return; //declined GamePlayer inviter = player.TempProperties.getProperty<object>("allianceinvite", null) as GamePlayer; if (player.Guild == null) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client, "Scripts.Player.Guild.NotMember"), eChatType.CT_System, eChatLoc.CL_SystemWindow); return; } if (inviter == null || inviter.Guild == null) { return; } if (!player.Guild.HasRank(player, Guild.eRank.Alli)) { player.Out.SendMessage(LanguageMgr.GetTranslation(player.Client, "Scripts.Player.Guild.NoPrivilages"), eChatType.CT_System, eChatLoc.CL_SystemWindow); return; } player.TempProperties.removeProperty("allianceinvite"); if (inviter.Guild.alliance == null) { //create alliance Alliance alli = new Alliance(); DBAlliance dballi = new DBAlliance(); dballi.AllianceName = inviter.Guild.Name; dballi.DBguildleader = null; dballi.Motd = ""; alli.Dballiance = dballi; alli.Guilds.Add(inviter.Guild); inviter.Guild.alliance = alli; inviter.Guild.AllianceId = inviter.Guild.alliance.Dballiance.ObjectId; } inviter.Guild.alliance.AddGuild(player.Guild); inviter.Guild.alliance.SaveIntoDatabase(); player.Guild.UpdateGuildWindow(); inviter.Guild.UpdateGuildWindow(); }
public override void RequestAllianceMembershipRequestTo(Alliance allianceToRequest) { throw new InvalidOperationException("Membership cannot be requested again"); }
/// <summary> /// Prepares the multiplayer game /// </summary> public void PrepareMultiplayerGame() { GameLobby lobby = (GameLobby)MenuManager.GetInstance().GetCurrentlyDisplayedMenu(); if (ChatServerConnectionManager.GetInstance().user.username == "Testy") { // Wait 5 seconds, this is purely for debugging to prevent I/O exceptions when // 2 local clients are accessing the same files. Thread.Sleep(2000); } foreach (User user in UserManager.GetInstance().users) { Game1.GetInstance().multiplayerGame.AddUser(user); } Alliance[] alliances = new Alliance[8]; for (int i = 0; i < alliances.Length; i++) { alliances[i] = new Alliance(); } for (int i = 0; i < lobby.GetDisplayPanelCount(); i++) { UserDisplayPanel panel = lobby.GetDisplayPanel(i); Alliance alli = alliances[Int32.Parse(panel.teamDropdown.GetSelectedOption()) - 1]; Player player = new Player(alli, panel.GetSelectedColor(), lobby.mapPreviewPanel.playerLocationGroup.GetMapLocationByButtonTextNumber(i + 1)); player.multiplayerID = panel.user.id; if (panel.user.id == ChatServerConnectionManager.GetInstance().user.id) { Game1.CURRENT_PLAYER = player; } alli.members.AddLast(player); } }
/// <summary> /// Creates a (pregame) match setup. All postgame data is put in later. /// </summary> /// <param name="num">Match number</param> /// <param name="blue">Blue alliance</param> /// <param name="red">Red alliance</param> public Match(int num, Alliance blue, Alliance red) { Number = num; RedAlliance = red; BlueAlliance = blue; Pregame = true; }
public override bool CanRequestAllianceMembershipRequestTo(Alliance allianceToRequest) { return false; }
/// <summary> /// コンストラクタ /// </summary> public ScenarioGlobalData() { // null動作が保証できれば削除 Rules = new ScenarioRules(); Axis = new Alliance(); Allies = new Alliance(); Comintern = new Alliance(); }
public override void RequestAllianceMembershipRequestTo(Alliance allianceToRequest) { if (CanRequestAllianceMembershipRequestTo(allianceToRequest)) { DomainEvents.Raise(new AllianceMembershipRequestedEvent { MembershipRequestedBy = _requestorOrganization, DateTime = DateTime.Now, MembershipRequestedTo = allianceToRequest }); } else { throw new InvalidOperationException("Membership cannot be requested anymore"); } }
/// <summary> /// Should be called when the map is finished with loading. /// </summary> public void FinishedLoadingMap() { Game1 game = Game1.GetInstance(); if (game.IsMultiplayerGame()) { // Do nothing, used to be something here } else { Alliance redAlliance = new Alliance(); Player humanPlayer = new Player(redAlliance, Color.Blue, this.tempPlayerLocations[0]); Game1.CURRENT_PLAYER = humanPlayer; humanPlayer.SpawnStartUnits(); Alliance greenAlliance = new Alliance(); Player aiPlayer = new Player(greenAlliance, Color.Purple, new Point((int)Game1.GetInstance().graphics.PreferredBackBufferWidth / 2, 200)); aiPlayer.SpawnStartUnits(); StateManager.GetInstance().gameState = StateManager.State.GameRunning; //SaveManager.GetInstance().SaveNodes("C:\\Users\\Wouter\\Desktop\\test.xml"); } game.map.miniMap = new MiniMap(game.map); game.map.miniMap.CreateMiniMap(true); game.drawOffset = new Vector2(Game1.CURRENT_PLAYER.startLocation.X - ( game.graphics.PreferredBackBufferWidth / 2 ), Game1.CURRENT_PLAYER.startLocation.Y - ( game.graphics.PreferredBackBufferHeight / 2 )); MouseManager.GetInstance().mouseClickedListeners += ((MouseClickListener)game).OnMouseClick; MouseManager.GetInstance().mouseReleasedListeners += ((MouseClickListener)game).OnMouseRelease; MouseManager.GetInstance().mouseMotionListeners += ((MouseMotionListener)game).OnMouseMotion; MouseManager.GetInstance().mouseDragListeners += ((MouseMotionListener)game).OnMouseDrag; }
public Match MakeMatch() { Alliance red = new Alliance(frc.LoadTeam(RedA), frc.LoadTeam(RedB), frc.LoadTeam(RedC)); Alliance blue = new Alliance(frc.LoadTeam(BlueA), frc.LoadTeam(BlueB), frc.LoadTeam(BlueC)); return new Match(MatchID, blue, red); }