public void Random_Generator_Test() { RandomHelper random = new RandomHelper(); for (int i = 1; i <= 100000; i++) { //Loger.Info(random.Number(4, false)); } }
public void MySampleTest() { var rnd = new RandomHelper(); var testBool = rnd.RandomBool(); var testString = rnd.RandomString(); var testStringAllowedEmpty = rnd.RandomString(true); var testEnum = rnd.RandomEnum<MySampleEnum>(); var testEnumWithExceptions = rnd.RandomEnum<MySampleEnum>(MySampleEnum.Val2); }
/// <summary> /// 根据ID获取QQ号。 /// </summary> /// <param name="userId">用户ID。</param> /// <returns>QQ号。</returns> public long GetQQNumberOf(long userId) { if (Status != ClientStatus.Active) { throw new InvalidOperationException("尚未登录,无法进行该操作"); } Logger.Instance.Debug("开始获取QQ号"); if (_qqNumberCache.ContainsKey(userId)) { Logger.Instance.Debug("加载了缓存的QQ号"); return(_qqNumberCache[userId]); } var qq = ((JObject) JObject.Parse(Client.GetStringAsync(ApiUrl.GetQQById, userId, Vfwebqq, RandomHelper.GetRandomDouble()).Result)[ "result"])["account"].Value <long>(); _qqNumberCache.Put(userId, qq); return(qq); }
private void UpdateRays(float elapsedSeconds) { if (this.RaysMesh.Groups.Count < 50 && RandomHelper.Probability(0.25)) { float x = 6f + RandomHelper.Centered(4.0); float num = RandomHelper.Between(0.5, (double)x / 2.5); Group group = this.RaysMesh.AddGroup(); group.Geometry = (IIndexedPrimitiveCollection) new IndexedUserPrimitives <FezVertexPositionTexture>(new FezVertexPositionTexture[6] { new FezVertexPositionTexture(new Vector3(0.0f, (float)((double)num / 2.0 * 0.100000001490116), 0.0f), new Vector2(0.0f, 0.0f)), new FezVertexPositionTexture(new Vector3(x, num / 2f, 0.0f), new Vector2(1f, 0.0f)), new FezVertexPositionTexture(new Vector3(x, (float)((double)num / 2.0 * 0.100000001490116), 0.0f), new Vector2(1f, 0.45f)), new FezVertexPositionTexture(new Vector3(x, (float)(-(double)num / 2.0 * 0.100000001490116), 0.0f), new Vector2(1f, 0.55f)), new FezVertexPositionTexture(new Vector3(x, (float)(-(double)num / 2.0), 0.0f), new Vector2(1f, 1f)), new FezVertexPositionTexture(new Vector3(0.0f, (float)(-(double)num / 2.0 * 0.100000001490116), 0.0f), new Vector2(0.0f, 1f)) }, new int[12] { 0, 1, 2, 0, 2, 5, 5, 2, 3, 5, 3, 4 }, PrimitiveType.TriangleList); group.CustomData = (object)new DotHost.RayState(); group.Material = new Material() { Diffuse = new Vector3(0.0f) }; group.Rotation = Quaternion.CreateFromAxisAngle(Vector3.Forward, RandomHelper.Between(0.0, 6.28318548202515)); } for (int i = this.RaysMesh.Groups.Count - 1; i >= 0; --i) { Group group = this.RaysMesh.Groups[i]; DotHost.RayState rayState = group.CustomData as DotHost.RayState; rayState.Age += elapsedSeconds * 0.15f; float num1 = Easing.EaseOut((double)Easing.EaseOut(Math.Sin((double)rayState.Age * 6.28318548202515 - 1.57079637050629) * 0.5 + 0.5, EasingType.Quintic), EasingType.Quintic); group.Material.Diffuse = Vector3.Lerp(Vector3.One, rayState.Tint.ToVector3(), 0.05f) * 0.15f * num1; float num2 = rayState.Speed; group.Rotation *= Quaternion.CreateFromAxisAngle(Vector3.Forward, (float)((double)elapsedSeconds * (double)num2 * (0.100000001490116 + (double)Easing.EaseIn((double)this.TimeAccumulator / 3.0, EasingType.Quadratic) * 0.200000002980232))); group.Scale = new Vector3((float)((double)num1 * 0.75 + 0.25), (float)((double)num1 * 0.5 + 0.5), 1f); if ((double)rayState.Age > 1.0) { this.RaysMesh.RemoveGroupAt(i); } } this.FlareMesh.Position = this.RaysMesh.Position = this.PlayerManager.Center; this.FlareMesh.Rotation = this.RaysMesh.Rotation = this.CameraManager.Rotation; this.RaysMesh.Scale = new Vector3(Easing.EaseIn((double)this.TimeAccumulator / 2.0, EasingType.Quadratic) + 1f); this.FlareMesh.Material.Opacity = (float)(0.125 + (double)Easing.EaseIn((double)FezMath.Saturate((float)(((double)this.TimeAccumulator - 2.0) / 3.0)), EasingType.Cubic) * 0.875); this.FlareMesh.Scale = Vector3.One + this.RaysMesh.Scale * Easing.EaseIn((double)Math.Max(this.TimeAccumulator - 2.5f, 0.0f) / 1.5, EasingType.Cubic) * 4f; if (this.KeyboardManager.GetKeyState(Keys.R) != FezButtonState.Pressed) { return; } this.TimeAccumulator = 0.0f; this.RaysMesh.ClearGroups(); }
Vector2 RV() { return(RandomHelper.RandomVector2(-11, 11, -11, 11)); }
//Returns spells that meet the specified criteria from the creatures spell list public SpellInfo SelectSpell(Unit target, SpellSchoolMask school, Mechanics mechanic, SelectTargetType targets, float rangeMin, float rangeMax, SelectEffect effect) { //No target so we can't cast if (target == null) { return(null); } //Silenced so we can't cast if (me.HasFlag(UnitFields.Flags, UnitFlags.Silenced)) { return(null); } //Using the extended script system we first create a list of viable spells SpellInfo[] apSpell = new SpellInfo[SharedConst.MaxCreatureSpells]; uint spellCount = 0; SpellInfo tempSpell = null; //Check if each spell is viable(set it to null if not) for (uint i = 0; i < SharedConst.MaxCreatureSpells; i++) { tempSpell = Global.SpellMgr.GetSpellInfo(me.m_spells[i]); //This spell doesn't exist if (tempSpell == null) { continue; } // Targets and Effects checked first as most used restrictions //Check the spell targets if specified if (targets != 0 && !Convert.ToBoolean(Global.ScriptMgr.spellSummaryStorage[me.m_spells[i]].Targets & (1 << ((int)targets - 1)))) { continue; } //Check the type of spell if we are looking for a specific spell type if (effect != 0 && !Convert.ToBoolean(Global.ScriptMgr.spellSummaryStorage[me.m_spells[i]].Effects & (1 << ((int)effect - 1)))) { continue; } //Check for school if specified if (school != 0 && (tempSpell.SchoolMask & school) == 0) { continue; } //Check for spell mechanic if specified if (mechanic != 0 && tempSpell.Mechanic != mechanic) { continue; } //Check if the spell meets our range requirements if (rangeMin != 0 && me.GetSpellMinRangeForTarget(target, tempSpell) < rangeMin) { continue; } if (rangeMax != 0 && me.GetSpellMaxRangeForTarget(target, tempSpell) > rangeMax) { continue; } //Check if our target is in range if (me.IsWithinDistInMap(target, me.GetSpellMinRangeForTarget(target, tempSpell)) || !me.IsWithinDistInMap(target, me.GetSpellMaxRangeForTarget(target, tempSpell))) { continue; } //All good so lets add it to the spell list apSpell[spellCount] = tempSpell; ++spellCount; } //We got our usable spells so now lets randomly pick one if (spellCount == 0) { return(null); } return(apSpell[RandomHelper.IRand(0, (int)(spellCount - 1))]); }
public async Task <ActionResult <ResponseModel> > Import() { var response = ResponseModelFactory.CreateInstance; //JArray lst = new JArray(); //JObject jsonResult = new JObject(); var lst = new List <WageInfo>(); //long size = 0; var fileNamePath = string.Empty; var requestPath = string.Empty; try { await using (_dbContext) { var files = Request.Form.Files; foreach (var file in files) { ////string fileName = DateTime.Now.ToString("MMddHHmmss") + file.FileName; //fileNamePath = DateTime.Now.ToString("MMddHHmmss") + file.FileName; ////size += file.Length; ////保存文件 ////物理路径 //string SavePath = Path.Combine(CeyhConfiguration.TheUploadFileSettings.UploadFolder, fileNamePath); ////using (FileStream fs = new FileStream(SavePath, FileMode.CreateNew)) ////{ //// file.CopyTo(fs); //// fs.Flush(); ////} //MemoryStream fs = new MemoryStream(); //file.CopyTo(fs); DataTable dt = OfficeHelper.ReadStreamToDataTable(file.OpenReadStream()); for (int i = 0; i < dt.Rows.Count; i++) { WageInfo obj = new WageInfo { Status = CommonEnum.Status.Normal, CreatedOn = DateTime.Now, Code = RandomHelper.GetRandomizer(8, true, false, true, true), CreatedByUserGuid = AuthContextService.CurrentUser.Guid, CreatedByUserName = AuthContextService.CurrentUser.DisplayName, RealName = dt.Rows[i][dt.Columns["真实姓名"]].ToString(), DepartmentCode = _dbContext.UserDepartment .SingleOrDefault(s => s.Name == dt.Rows[i][dt.Columns["部门"]].ToString().Trim()) ?.Code, PositionCode = _dbContext.UserPosition.SingleOrDefault(s => s.Name == dt.Rows[i][dt.Columns["职位"]].ToString().Trim())?.Code, StartDate = DateTime.Parse(dt.Rows[i][dt.Columns["开始日期"]].ToString() ?.Replace("【", "") .Replace("】", "") ?? string.Empty), EndDate = DateTime.Parse(dt.Rows[i][dt.Columns["结束日期"]].ToString() ?.Replace("【", "") .Replace("】", "") ?? throw new InvalidOperationException()), TotalWage = decimal.Parse(dt.Rows[i][dt.Columns["应发工资"]].ToString() ?? string.Empty), BaseWage = decimal.Parse(dt.Rows[i][dt.Columns["基本工资"]].ToString() ?? string.Empty), WorkDays = int.Parse(dt.Rows[i][dt.Columns["工作天数"]].ToString() ?? throw new InvalidOperationException()), OTWage = decimal.Parse(dt.Rows[i][dt.Columns["加班工资"]].ToString() ?? string.Empty), OTDays = int.Parse(dt.Rows[i][dt.Columns["加班天数"]].ToString() ?? string.Empty), PerformanceWage = decimal.Parse(dt.Rows[i][dt.Columns["绩效工资"]].ToString() ?? string.Empty), ReissueWage = decimal.Parse(dt.Rows[i][dt.Columns["补发工资"]].ToString() ?? string.Empty), Subsidy = decimal.Parse(dt.Rows[i][dt.Columns["补贴"]].ToString() ?? string.Empty), Commission = decimal.Parse(dt.Rows[i][dt.Columns["提成"]].ToString() ?? string.Empty), Bonus = decimal.Parse(dt.Rows[i][dt.Columns["奖金"]].ToString() ?? string.Empty), }; //obj.StartDate = DateTime.Parse($"{dt.Rows[i][dt.Columns["开始日期"]].ToString().Split('-')[2]}-" + // $"{dt.Rows[i][dt.Columns["开始日期"]].ToString().Split('-')[1].Replace("月","")}-" + // $"{dt.Rows[i][dt.Columns["开始日期"]].ToString().Split('-')[0]}"); //obj.EndDate = DateTime.Parse($"{dt.Rows[i][dt.Columns["结束日期"]].ToString().Split('-')[2]}-" + // $"{dt.Rows[i][dt.Columns["结束日期"]].ToString().Split('-')[1].Replace("月", "")}-" + // $"{dt.Rows[i][dt.Columns["结束日期"]].ToString().Split('-')[0]}"); var adds = dt.Rows[i][dt.Columns["额外工资"]].ToString()?.Split(';'); obj.Additions = (adds ?? Array.Empty <string>()).Select(a => new { val = a.Split(':')[1], remark = a.Split(':')[0] }).ToJson(); obj.SocialSecurity = decimal.Parse(dt.Rows[i][dt.Columns["社保"]].ToString() ?? string.Empty); obj.AccumulationFund = decimal.Parse(dt.Rows[i][dt.Columns["公积金"]].ToString() ?? string.Empty); obj.IncomeTax = decimal.Parse(dt.Rows[i][dt.Columns["个税"]].ToString() ?? string.Empty); obj.Deductions = dt.Rows[i][dt.Columns["额外扣除"]].ToString() ?.Split(';'). Select(a => new { val = a.Split(':')[1], remark = a.Split(':')[0] }).ToJson(); //for (int j = 0; j < dt.Columns.Count; j++) //{ //} lst.Add(obj); } var count = lst.Count / 100 + 1; for (var i = 0; i < count; i++) { var childish = lst.Skip(i).Take(1000).ToList(); await _dbContext.AddRangeAsync(childish); await _dbContext.SaveChangesAsync(); } } } //string url = Request.HttpContext.Connection.RemoteIpAddress.ToStringExt()+":"+ Request.HttpContext.Connection.RemotePort.ToStringExt(); } catch (Exception ex) { response.SetError("上传文件错误信息列表错误:" + ex.ToString()); return(response); } return(response); }
//Please do not change GetPokeStops() in this file, it's specifically set //to only find stops within 40 meters //this is for gpx pathing, we are not going to the pokestops, //so do not make it more than 40 because it will never get close to those stops. public static async Task Execute() { if (Logic._client.Settings.GPXIgnorePokestops) { return; } var pokestops = await Inventory.GetPokestops(true); while (pokestops.Any()) { var pokestop = pokestops.OrderBy( i => LocationUtils.CalculateDistanceInMeters(Logic._client.CurrentLatitude, Logic._client.CurrentLongitude, i.Latitude, i.Longitude)).First(); pokestops.Remove(pokestop); var distance = LocationUtils.CalculateDistanceInMeters(Logic._client.CurrentLatitude, Logic._client.CurrentLongitude, pokestop.Latitude, pokestop.Longitude); var fortInfo = await Logic._client.Fort.GetFort(pokestop.Id, pokestop.Latitude, pokestop.Longitude); var latlngDebug = string.Empty; if (Logic._client.Settings.DebugMode) { latlngDebug = $"| Latitude: {pokestop.Latitude} - Longitude: {pokestop.Longitude}"; } Logger.Write($"Name: {fortInfo.Name} in {distance:0.##} m distance {latlngDebug}", LogLevel.Pokestop); //Catch Lure Pokemon if (pokestop.LureInfo != null && Logic._client.Settings.CatchLuredPokemon) { await CatchLurePokemonsTask.Execute(pokestop); } var timesZeroXPawarded = 0; var fortTry = 0; //Current check const int retryNumber = 50; //How many times it needs to check to clear softban const int zeroCheck = 5; //How many times it checks fort before it thinks it's softban do { var fortSearch = await Logic._client.Fort.SearchFort(pokestop.Id, pokestop.Latitude, pokestop.Longitude); if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0) { timesZeroXPawarded = 0; } if (fortSearch.ExperienceAwarded == 0) { timesZeroXPawarded++; if (timesZeroXPawarded <= zeroCheck) { continue; } if ((int)fortSearch.CooldownCompleteTimestampMs != 0) { break; // Check if successfully looted, if so program can continue as this was "false alarm". } fortTry += 1; if (Logic._client.Settings.DebugMode) { Logger.Write($"Seems your Soft-Banned. Trying to Unban via Pokestop Spins. Retry {fortTry} of {retryNumber - zeroCheck}", LogLevel.Warning); } await RandomHelper.RandomDelay(75, 100); } else { BotStats.ExperienceThisSession += fortSearch.ExperienceAwarded; BotStats.UpdateConsoleTitle(); Logger.Write($"XP: {fortSearch.ExperienceAwarded}, Gems: {fortSearch.GemsAwarded}, Items: {StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded)}", LogLevel.Pokestop); RecycleItemsTask._recycleCounter++; HatchEggsTask._hatchUpdateDelayGPX++; break; //Continue with program as loot was succesfull. } } while (fortTry < retryNumber - zeroCheck); //Stop trying if softban is cleaned earlier or if 40 times fort looting failed. if (RecycleItemsTask._recycleCounter >= 5) { await RecycleItemsTask.Execute(); } if (HatchEggsTask._hatchUpdateDelayGPX >= 5) { await HatchEggsTask.Execute(); } } }
private static string GenerateEmail(string nameSurname) { return(GenerateUsername(nameSurname) + "@" + RandomHelper.GetRandomOf(EmailProviders)); }
protected override async void Init() { InitialRotation = new Quaternion(180, 270, -30); var cache = Application.ResourceCache; var node = Node; var model = node.CreateComponent <StaticModel>(); model.Model = cache.GetModel(Assets.Models.Enemy1); model.SetMaterial(cache.GetMaterial(Assets.Materials.Enemy1).Clone("")); node.SetScale(RandomHelper.NextRandom(0.1f, 0.12f)); node.Position = new Vector3(0f, 5f, 0f); // load weapons: node.AddComponent(new XamarinCube()); node.Position = new Vector3(3 * (RandomHelper.NextBoolRandom() ? 1 : -1), RandomHelper.NextRandom(0, 2), 0); await Node.RunActionsAsync(new MoveTo(1f, new Vector3(RandomHelper.NextRandom(-2, 2), RandomHelper.NextRandom(2, 4), 0))); MoveRandomly(minX: -2f, maxX: 2f, minY: -1f, maxY: 1f, duration: 0.5f); StartShooting(); }
public static async Task Execute() { var distanceFromStart = LocationUtils.CalculateDistanceInMeters( Logic._client.Settings.DefaultLatitude, Logic._client.Settings.DefaultLongitude, Logic._client.CurrentLatitude, Logic._client.CurrentLongitude); // Edge case for when the client somehow ends up outside the defined radius if (Logic._client.Settings.MaxTravelDistanceInMeters != 0 && distanceFromStart > Logic._client.Settings.MaxTravelDistanceInMeters) { Logger.Write( $"You're outside of your defined radius! Walking to Default Coords ({distanceFromStart:0.##}m away). Is your LastCoords.ini file correct?", LogLevel.Warning); await Navigation.HumanLikeWalking( new GeoUtils(Logic._client.Settings.DefaultLatitude, Logic._client.Settings.DefaultLongitude), async() => { // Catch normal map Pokemon await CatchMapPokemonsTask.Execute(); //Catch Incense Pokemon await CatchIncensePokemonsTask.Execute(); return(true); }); } var pokestops = await Inventory.GetPokestops(); if (pokestops == null || !pokestops.Any()) { Logger.Write( "No usable PokeStops found in your area. Reasons: Softbanned - Server Issues - MaxTravelDistanceInMeters too small", LogLevel.Warning); return; } Logger.Write($"Found {pokestops.Count()} {(pokestops.Count() == 1 ? "Pokestop" : "Pokestops")}", LogLevel.Info); Gui.SetPokestopMarker(pokestops); while (pokestops.Any()) { if (Logic._client.Settings.UseCSVExport && ExportPokemonToCsv._lastExportTime.AddMinutes(Logic._client.Settings.CSVExportInMinutes).Ticks < DateTime.Now.Ticks) { var _playerProfile = await Logic._client.Player.GetPlayer(); await ExportPokemonToCsv.Execute(_playerProfile.PlayerData); } if (Logic._client.Settings.UseLuckyEggs) { await UseLuckyEggTask.Execute(); } if (Logic._client.Settings.CatchIncensePokemon) { await UseIncenseTask.Execute(); } var pokestopwithcooldown = pokestops.Where(p => p.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime()).FirstOrDefault(); if (pokestopwithcooldown != null) { pokestops.Remove(pokestopwithcooldown); } var pokestop = pokestops.Where(p => p.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime()) .OrderBy( i => LocationUtils.CalculateDistanceInMeters(Logic._client.CurrentLatitude, Logic._client.CurrentLongitude, i.Latitude, i.Longitude)).First(); var lured = string.Empty; var distance = LocationUtils.CalculateDistanceInMeters(Logic._client.CurrentLatitude, Logic._client.CurrentLongitude, pokestop.Latitude, pokestop.Longitude); if (distance > 100) { var lurePokestop = pokestops.FirstOrDefault(x => x.LureInfo != null); if (lurePokestop != null) { distance = LocationUtils.CalculateDistanceInMeters(Logic._client.CurrentLatitude, Logic._client.CurrentLongitude, pokestop.Latitude, pokestop.Longitude); if (distance < 200) { lured = " is Lured"; pokestop = lurePokestop; } else { pokestops.Remove(pokestop); } } } else { pokestops.Remove(pokestop); } var fortInfo = await Logic._client.Fort.GetFort(pokestop.Id, pokestop.Latitude, pokestop.Longitude); var latlngDebug = string.Empty; if (Logic._client.Settings.DebugMode) { latlngDebug = $" | Latitude: {pokestop.Latitude} - Longitude: {pokestop.Longitude}"; } Logger.Write($"Name: {fortInfo.Name} in {distance:0.##} m distance{lured}{latlngDebug}", LogLevel.Pokestop); if (Logic._client.Settings.MovementBy == "UseTeleportInsteadOfWalking") { await Logic._client.Player.UpdatePlayerLocation(pokestop.Latitude, pokestop.Longitude, Logic._client.Settings.DefaultAltitude); await RandomHelper.RandomDelay(500); Logger.Write($"Using Teleport instead of Walking!", LogLevel.Navigation); } else { await Navigation.HumanLikeWalking(new GeoUtils(pokestop.Latitude, pokestop.Longitude), async() => { // Catch normal map Pokemon await CatchMapPokemonsTask.Execute(); //Catch Incense Pokemon await CatchIncensePokemonsTask.Execute(); return(true); }); } //Catch Lure Pokemon if (pokestop.LureInfo != null && Logic._client.Settings.CatchLuredPokemon) { await CatchLurePokemonsTask.Execute(pokestop); } var timesZeroXPawarded = 0; var fortTry = 0; //Current check const int retryNumber = 45; //How many times it needs to check to clear softban const int zeroCheck = 5; //How many times it checks fort before it thinks it's softban do { var fortSearch = await Logic._client.Fort.SearchFort(pokestop.Id, pokestop.Latitude, pokestop.Longitude); if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0) { timesZeroXPawarded = 0; } if (fortSearch.ExperienceAwarded == 0) { if (fortSearch.Result == FortSearchResponse.Types.Result.InCooldownPeriod) { Logger.Write("Pokestop is on Cooldown", LogLevel.Debug); break; } timesZeroXPawarded++; if (timesZeroXPawarded > zeroCheck) { fortTry += 1; if (Logic._client.Settings.DebugMode) { Logger.Write( $"Seems your Soft-Banned. Trying to Unban via Pokestop Spins. Retry {fortTry} of {retryNumber - zeroCheck}", LogLevel.Warning); } await RandomHelper.RandomDelay(450); } } else if (fortSearch.ExperienceAwarded != 0) { BotStats.ExperienceThisSession += fortSearch.ExperienceAwarded; BotStats.UpdateConsoleTitle(); Logger.Write($"XP: {fortSearch.ExperienceAwarded}, Gems: {fortSearch.GemsAwarded}, Items: {StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded)}", LogLevel.Pokestop); RecycleItemsTask._recycleCounter++; HatchEggsTask._hatchUpdateDelay++; break; //Continue with program as loot was succesfull. } } while (fortTry < retryNumber - zeroCheck); //Stop trying if softban is cleaned earlier or if 40 times fort looting failed. if (RecycleItemsTask._recycleCounter >= 5) { await RecycleItemsTask.Execute(); } if (HatchEggsTask._hatchUpdateDelay >= 15) { await HatchEggsTask.Execute(); } } }
private BattleResult GetBattleResult(Unit Attacker, Squad AttackerSquad, float DamageModifier, Unit Defender, Squad DefenderSquad, bool ActivateSkills, bool CalculateCritical) { ActivateAutomaticSkills(AttackerSquad, Attacker, DeathmatchSkillRequirement.BeforeAttackRequirementName, DefenderSquad, Defender); ActivateAutomaticSkills(DefenderSquad, Defender, DeathmatchSkillRequirement.BeforeGettingAttackedRequirementName, AttackerSquad, Attacker); BattleResult Result; int BaseHitRate; BaseHitRate = CalculateHitRate(Attacker, AttackerSquad, Defender, DefenderSquad, Defender.BattleDefenseChoice); bool AttackHit = RandomHelper.RandomActivationCheck(BaseHitRate); if (AttackHit) { if (ActivateSkills) { ActivateAutomaticSkills(AttackerSquad, Attacker, DeathmatchSkillRequirement.BeforeHitRequirementName, DefenderSquad, Defender); ActivateAutomaticSkills(DefenderSquad, Defender, DeathmatchSkillRequirement.BeforeGettingHitRequirementName, AttackerSquad, Attacker); } Result = DamageFormula(Attacker, AttackerSquad, DamageModifier, Defender, DefenderSquad, Defender.BattleDefenseChoice, CalculateCritical); } else { if (ActivateSkills) { ActivateAutomaticSkills(AttackerSquad, Attacker, DeathmatchSkillRequirement.BeforeMissRequirementName, DefenderSquad, Defender); ActivateAutomaticSkills(DefenderSquad, Defender, DeathmatchSkillRequirement.BeforeGettingMissedRequirementName, AttackerSquad, Attacker); } Result = new BattleResult(); Result.AttackDamage = 0; Result.AttackMissed = true; } Result.Accuracy = BaseHitRate; Result.Target = Defender; //Remove EN from the weapon cost. if (Attacker.CurrentAttack.ENCost > 0) { Result.AttackAttackerFinalEN = Math.Max(0, Attacker.EN - (Attacker.CurrentAttack.ENCost + Attacker.Boosts.ENCostModifier)); } else { Result.AttackAttackerFinalEN = Attacker.EN; } GlobalBattleContext.Result = Result; if (ActivateSkills) { Attacker.UpdateSkillsLifetime(SkillEffect.LifetimeTypeOnAttack); Defender.UpdateSkillsLifetime(SkillEffect.LifetimeTypeOnEnemyAttack); if (AttackHit) { Attacker.UpdateSkillsLifetime(SkillEffect.LifetimeTypeOnHit); Defender.UpdateSkillsLifetime(SkillEffect.LifetimeTypeOnEnemyHit); ActivateAutomaticSkills(AttackerSquad, Attacker, DeathmatchSkillRequirement.AfterHitRequirementName, DefenderSquad, Defender); ActivateAutomaticSkills(DefenderSquad, Defender, DeathmatchSkillRequirement.AfterGettingHitRequirementName, AttackerSquad, Attacker); } else { ActivateAutomaticSkills(AttackerSquad, Attacker, DeathmatchSkillRequirement.AfterMissRequirementName, DefenderSquad, Defender); ActivateAutomaticSkills(DefenderSquad, Defender, DeathmatchSkillRequirement.AfterGettingMissedRequirementName, AttackerSquad, Attacker); } ActivateAutomaticSkills(AttackerSquad, Attacker, DeathmatchSkillRequirement.AfterAttackRequirementName, DefenderSquad, Defender); ActivateAutomaticSkills(DefenderSquad, Defender, DeathmatchSkillRequirement.AfterGettingAttackedRequirementName, AttackerSquad, Attacker); } return(Result); }
protected override async ETTask Run(Player player, C2M_RoomOpRequest message, M2C_RoomOpResponse response, Action reply) { Room room = player.Room; switch (message.Op) { case RoomOpType.Ready: room.Ready(player); break; case RoomOpType.CancelReady: room.Ready(player, false); break; case RoomOpType.NotPlay: player.NotPop(); break; case RoomOpType.Destroy: break; case RoomOpType.MockCards: var test = player.GetComponent <TestCardComponent>(); if (test == null) { test = player.AddComponent <TestCardComponent>(); } test.Cards = message.Cards; test.Seat = player.SeatIndex; break; case RoomOpType.MockPlayer_Add: if (room.TryGetSeatIndex(out int seat)) { Player mockPlayer = EntityFactory.Create <Player, long, Room>(room.Domain, 0, room); mockPlayer.AddComponent <MailBoxComponent>().IgnoreNotFondHandlerException = true; mockPlayer.SeatIndex = seat; var playerServer = mockPlayer.AddComponent <PlayerServer, long>(mockPlayer.InstanceId); playerServer.Flags = PlayerFlags.Robot; mockPlayer.AddComponent <RobotProxy>(); var mockModel = mockPlayer.AddComponent <PlayerModel>(); mockModel.NickName = "T" + RandomHelper.RandomNumber(1, 1000); room.Enter(mockPlayer); } break; case RoomOpType.MockPlayer_Remove: for (int i = 0; i < room.Players.Length; i++) { var p = room.Players[i]; if (p == null || p.GetComponent <PlayerServer>().Flags == PlayerFlags.Player) { continue; } room.Exit(p); break; } break; case RoomOpType.MockPlayer_Ready: for (int i = 0; i < room.Players.Length; i++) { var p = room.Players[i]; if (p == null || p.GetComponent <PlayerServer>().Flags == PlayerFlags.Player) { continue; } room.Ready(p); } break; case RoomOpType.MockPlayer_CancelReady: break; case RoomOpType.MockPlayer_SwitchSeat: break; } reply(); await ETTask.CompletedTask; }
private int Range(int max) { return(RandomHelper.Range(MapPosition, Key + _randomIndex++, max)); }
protected RandomHelper GetRandomHelper() { return(RandomHelper.GetInstance()); }
/// <summary> /// Default constructor for a prebuilt heightmap. /// </summary> /// <param name="width"></param> /// <param name="depth"></param> /// <param name="min"></param> /// <param name="max"></param> /// <param name="data"></param> /// <param name="randomSeed"></param> public Heightmap(int width, int depth, float min, float max, float[] data, int randomSeed) { _width = width; _depth = depth; _minimumHeight = min; _maximumHeight = max; _randomSeed = randomSeed; if (data != null) _heightValues = (float[]) data.Clone(); _random = new RandomHelper(randomSeed); }
public int RandomIntGen(int x, int y) { return(RandomHelper.Range(x, y, Key, 1000)); }
private async Task ExecuteCatchAllNearbyPokemons() { var client = _client; var mapObjects = await client.GetMapObjects(); //var pokemons = mapObjects.MapCells.SelectMany(i => i.CatchablePokemons); var pokemons = mapObjects.MapCells.SelectMany(i => i.CatchablePokemons) .OrderBy( i => LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, i.Latitude, i.Longitude)); if (pokemons != null && pokemons.Any()) { Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"Found {pokemons.Count()} catchable Pokemon(s)."); } foreach (var pokemon in pokemons) { count++; if (count >= 3) { count = 0; await StatsLog(client); if (_clientSettings.EvolvePokemonsIfEnoughCandy) { await EvolveAllPokemonWithEnoughCandy(); } await TransferDuplicatePokemon(_clientSettings.keepPokemonsThatCanEvolve); await RecycleItems(); } if (_clientSettings.catchPokemonSkipList.Contains(pokemon.PokemonId)) { Logger.ColoredConsoleWrite(ConsoleColor.Green, "Skipped Pokemon: " + pokemon.PokemonId); continue; } var distance = LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, pokemon.Latitude, pokemon.Longitude); await Task.Delay(distance > 100? 1000 : 100); var encounterPokemonResponse = await _client.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnpointId); if (encounterPokemonResponse.Status == EncounterResponse.Types.Status.EncounterSuccess) { var bestPokeball = await GetBestBall(encounterPokemonResponse?.WildPokemon); if (bestPokeball == MiscEnums.Item.ITEM_UNKNOWN) { Logger.ColoredConsoleWrite(ConsoleColor.Red, $"We dont own Pokeballs! - We missed a {pokemon.PokemonId} with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp}"); return; } CatchPokemonResponse caughtPokemonResponse; do { var inventoryBerries = await _inventory.GetItems(); var probability = encounterPokemonResponse?.CaptureProbability?.CaptureProbability_?.FirstOrDefault(); var bestBerry = await GetBestBerry(encounterPokemonResponse?.WildPokemon); var berries = inventoryBerries.Where(p => (ItemId)p.Item_ == bestBerry).FirstOrDefault(); if (bestBerry != ItemId.ItemUnknown && probability.HasValue && probability.Value < 0.35) { //Throw berry is we can var useRaspberry = await _client.UseCaptureItem(pokemon.EncounterId, bestBerry, pokemon.SpawnpointId); Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Used {bestBerry}. Remaining: {berries.Count}.", LogLevel.Info); await RandomHelper.RandomDelay(50, 200); } caughtPokemonResponse = await _client.CatchPokemon(pokemon.EncounterId, pokemon.SpawnpointId, pokemon.Latitude, pokemon.Longitude, bestPokeball); }while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape); if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess) { foreach (int xp in caughtPokemonResponse.Scores.Xp) { _botStats.addExperience(xp); } Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"We caught a {StringUtils.getPokemonNameByLanguage(_clientSettings, pokemon.PokemonId)} with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp} ({PokemonInfo.CalculatePokemonPerfection(encounterPokemonResponse?.WildPokemon.PokemonData)}% perfect) using a {bestPokeball} and we got {caughtPokemonResponse.Scores.Xp.Sum()} XP."); //try //{ // var r = (HttpWebRequest)WebRequest.Create("http://pokemon.becher.xyz/index.php?pokeName=" + pokemon.PokemonId); // var rp = (HttpWebResponse)r.GetResponse(); // var rps = new StreamReader(rp.GetResponseStream()).ReadToEnd(); // Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"We caught a {pokemon.PokemonId} ({rps}) with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp} using a {bestPokeball}"); //} catch (Exception) //{ // Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"We caught a {pokemon.PokemonId} (Language Server Offline) with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp} using a {bestPokeball}"); //} _botStats.addPokemon(1); } else { Logger.ColoredConsoleWrite(ConsoleColor.DarkYellow, $"{StringUtils.getPokemonNameByLanguage(_clientSettings, pokemon.PokemonId)} with CP {encounterPokemonResponse?.WildPokemon?.PokemonData?.Cp} ({PokemonInfo.CalculatePokemonPerfection(encounterPokemonResponse?.WildPokemon.PokemonData)} % perfect) got away while using a {bestPokeball}.."); failed_softban++; } } else { Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Error Catching Pokemon: {encounterPokemonResponse?.Status}"); } await RandomHelper.RandomDelay(50, 200); } }
private async Task BuildForInternalAsync(Tenant tenant) { //Create Organization Units var organizationUnits = new List <OrganizationUnit>(); var producing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Producing"); var researchAndDevelopment = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Research & Development", producing); var ivrProducts = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "IVR Related Products", researchAndDevelopment); var voiceTech = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Voice Technologies", researchAndDevelopment); var inhouseProjects = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Inhouse Projects", researchAndDevelopment); var qualityManagement = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Quality Management", producing); var testing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Testing", producing); var selling = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Selling"); var marketing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Marketing", selling); var sales = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Sales", selling); var custRelations = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Customer Relations", selling); var supporting = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Supporting"); var buying = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Buying", supporting); var humanResources = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Human Resources", supporting); //Create users var users = _randomUserGenerator.GetRandomUsers(RandomHelper.GetRandom(12, 26), tenant.Id); foreach (var user in users) { //Create the user await _userManager.CreateAsync(user); await CurrentUnitOfWork.SaveChangesAsync(); //Add to roles _userManager.AddToRole(user.Id, StaticRoleNames.Tenants.User); //Add to OUs var randomOus = MyRandomHelper.GenerateRandomizedList(organizationUnits).Take(RandomHelper.GetRandom(0, 3)); foreach (var ou in randomOus) { await _userManager.AddToOrganizationUnitAsync(user, ou); } //Set profile picture if (RandomHelper.GetRandom(100) < 70) //A user will have a profile picture in 70% probability. { await SetRandomProfilePictureAsync(user); } } //Set a picture to admin! var admin = _userManager.FindByName(User.AdminUserName); await SetRandomProfilePictureAsync(admin); }
public DemoScenario(IServiceProvider serviceProvider) : base(serviceProvider) { AddStep(new SleepScenarioStep("Wait1", RandomHelper.GetRandom(1000, 5000))); AddStep(new SleepScenarioStep("Wait2", RandomHelper.GetRandom(2000, 6000))); }
public int RandomBallsoulOthercolorForWCH() { return(_ballsoulOtherColorList[RandomHelper.GetInt32WithoutMax(0, _ballsoulOtherColorCount)]); }
public void RandomHelperTest(int value, int sourceMin, int sourceMax, int destMin, int destMax, int expectedValue) { var normalize = RandomHelper.Normalize(value, sourceMin, sourceMax, destMin, destMax); normalize.Should().Be(expectedValue); }
public void Generer() { int nombreHeal = 0; int nombreMonstres = 0; int nombreVide = 0; for (int i = 0; i < _dimension; i++) { for (int j = 0; j < _dimension; j++) { var lieu = new Lieu(); int res = lieu.Generer(); _carte[i, j] = lieu; //Code de log switch (res) { case 0: nombreVide++; break; case 1: nombreMonstres++; break; case 2: nombreHeal++; break; } } } var finX = RandomHelper.GetRandom(0, _dimension - 1); var finY = RandomHelper.GetRandom(0, _dimension - 1); var marchandX = RandomHelper.GetRandom(0, _dimension - 1); var marchandY = RandomHelper.GetRandom(0, _dimension - 1); PosX = RandomHelper.GetRandom(0, _dimension - 1); PosY = RandomHelper.GetRandom(0, _dimension - 1); while (finX == PosX && finY == PosY) { PosX = RandomHelper.GetRandom(0, _dimension - 1); PosY = RandomHelper.GetRandom(0, _dimension - 1); } while (finX == marchandX && finY == marchandY && PosX == marchandX && PosY == marchandY) { marchandX = RandomHelper.GetRandom(0, _dimension - 1); marchandY = RandomHelper.GetRandom(0, _dimension - 1); } Lieu fin = _carte[finX, finY]; fin.EstFin = true; fin.Monstre = new Monstre { Pv = 250, DegatMax = 25, Nom = "George Abitbol" }; Lieu marchand = _carte[marchandX, marchandY]; marchand.EstMarchant = true; marchand.EstCaseSoin = false; Console.WriteLine($"La carte a été générée avec {nombreVide} cases vides, {nombreMonstres} monstres et {nombreHeal} cases de soin"); Console.WriteLine($"Départ à la case [{PosX},{PosY}], princesse à la case [{finX},{finY}]"); }
LfgCompatibility CheckCompatibility(List <ObjectGuid> check) { string strGuids = ConcatenateGuids(check); LfgProposal proposal = new LfgProposal(); List <uint> proposalDungeons; Dictionary <ObjectGuid, ObjectGuid> proposalGroups = new Dictionary <ObjectGuid, ObjectGuid>(); Dictionary <ObjectGuid, LfgRoles> proposalRoles = new Dictionary <ObjectGuid, LfgRoles>(); // Check for correct size if (check.Count > MapConst.MaxGroupSize || check.Empty()) { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}): Size wrong - Not compatibles", strGuids); return(LfgCompatibility.WrongGroupSize); } // Check all-but-new compatiblitity if (check.Count > 2) { ObjectGuid frontGuid = check.First(); check.RemoveAt(0); // Check all-but-new compatibilities (New, A, B, C, D) -. check(A, B, C, D) LfgCompatibility child_compatibles = CheckCompatibility(check); if (child_compatibles < LfgCompatibility.WithLessPlayers) // Group not compatible { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) child {1} not compatibles", strGuids, ConcatenateGuids(check)); SetCompatibles(strGuids, child_compatibles); return(child_compatibles); } check.Insert(0, frontGuid); } // Check if more than one LFG group and number of players joining byte numPlayers = 0; byte numLfgGroups = 0; foreach (var guid in check) { if (!(numLfgGroups < 2) && !(numPlayers <= MapConst.MaxGroupSize)) { break; } var itQueue = QueueDataStore.LookupByKey(guid); if (itQueue == null) { Log.outError(LogFilter.Lfg, "CheckCompatibility: [{0}] is not queued but listed as queued!", guid); RemoveFromQueue(guid); return(LfgCompatibility.Pending); } // Store group so we don't need to call Mgr to get it later (if it's player group will be 0 otherwise would have joined as group) foreach (var it2 in itQueue.roles) { proposalGroups[it2.Key] = guid.IsPlayer() ? guid : ObjectGuid.Empty; } numPlayers += (byte)itQueue.roles.Count; if (Global.LFGMgr.IsLfgGroup(guid)) { if (numLfgGroups == 0) { proposal.group = guid; } ++numLfgGroups; } } // Group with less that MAXGROUPSIZE members always compatible if (check.Count == 1 && numPlayers != MapConst.MaxGroupSize) { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) sigle group. Compatibles", strGuids); var guid = check.First(); var itQueue = QueueDataStore.LookupByKey(guid); LfgCompatibilityData data = new LfgCompatibilityData(LfgCompatibility.WithLessPlayers); data.roles = itQueue.roles; Global.LFGMgr.CheckGroupRoles(data.roles); UpdateBestCompatibleInQueue(guid, itQueue, strGuids, data.roles); SetCompatibilityData(strGuids, data); return(LfgCompatibility.WithLessPlayers); } if (numLfgGroups > 1) { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) More than one Lfggroup ({1})", strGuids, numLfgGroups); SetCompatibles(strGuids, LfgCompatibility.MultipleLfgGroups); return(LfgCompatibility.MultipleLfgGroups); } if (numPlayers > MapConst.MaxGroupSize) { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) Too much players ({1})", strGuids, numPlayers); SetCompatibles(strGuids, LfgCompatibility.TooMuchPlayers); return(LfgCompatibility.TooMuchPlayers); } // If it's single group no need to check for duplicate players, ignores, bad roles or bad dungeons as it's been checked before joining if (check.Count > 1) { foreach (var it in check) { Dictionary <ObjectGuid, LfgRoles> roles = QueueDataStore[it].roles; foreach (var rolePair in roles) { KeyValuePair <ObjectGuid, LfgRoles> itPlayer = new KeyValuePair <ObjectGuid, LfgRoles>(); foreach (var _player in proposalRoles) { itPlayer = _player; if (rolePair.Key == itPlayer.Key) { Log.outError(LogFilter.Lfg, "CheckCompatibility: ERROR! Player multiple times in queue! [{0}]", rolePair.Key); } else if (Global.LFGMgr.HasIgnore(rolePair.Key, itPlayer.Key)) { break; } } if (itPlayer.Key == proposalRoles.LastOrDefault().Key) { proposalRoles[rolePair.Key] = rolePair.Value; } } } byte playersize = (byte)(numPlayers - proposalRoles.Count); if (playersize != 0) { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) not compatible, {1} players are ignoring each other", strGuids, playersize); SetCompatibles(strGuids, LfgCompatibility.HasIgnores); return(LfgCompatibility.HasIgnores); } StringBuilder o; Dictionary <ObjectGuid, LfgRoles> debugRoles = proposalRoles; if (!Global.LFGMgr.CheckGroupRoles(proposalRoles)) { o = new StringBuilder(); foreach (var it in debugRoles) { o.AppendFormat(", {0}: {1}", it.Key, GetRolesString(it.Value)); } Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) Roles not compatible{1}", strGuids, o.ToString()); SetCompatibles(strGuids, LfgCompatibility.NoRoles); return(LfgCompatibility.NoRoles); } var itguid = check.First(); proposalDungeons = QueueDataStore[itguid].dungeons; o = new StringBuilder(); o.AppendFormat(", {0}: ({1})", itguid, Global.LFGMgr.ConcatenateDungeons(proposalDungeons)); foreach (var guid in check) { if (guid == itguid) { continue; } List <uint> dungeons = QueueDataStore[itguid].dungeons; o.AppendFormat(", {0}: ({1})", guid, Global.LFGMgr.ConcatenateDungeons(dungeons)); List <uint> temporal = proposalDungeons.Intersect(dungeons).ToList(); proposalDungeons = temporal; } if (proposalDungeons.Empty()) { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) No compatible dungeons{1}", strGuids, o.ToString()); SetCompatibles(strGuids, LfgCompatibility.NoDungeons); return(LfgCompatibility.NoDungeons); } } else { ObjectGuid gguid = check.First(); LfgQueueData queue = QueueDataStore[gguid]; proposalDungeons = queue.dungeons; proposalRoles = queue.roles; Global.LFGMgr.CheckGroupRoles(proposalRoles); // assing new roles } // Enough players? if (numPlayers != MapConst.MaxGroupSize) { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) Compatibles but not enough players({1})", strGuids, numPlayers); LfgCompatibilityData data = new LfgCompatibilityData(LfgCompatibility.WithLessPlayers); data.roles = proposalRoles; foreach (var guid in check) { var queueData = QueueDataStore.LookupByKey(guid); UpdateBestCompatibleInQueue(guid, queueData, strGuids, data.roles); } SetCompatibilityData(strGuids, data); return(LfgCompatibility.WithLessPlayers); } ObjectGuid _guid = check.First(); proposal.queues = check; proposal.isNew = numLfgGroups != 1 || Global.LFGMgr.GetOldState(_guid) != LfgState.Dungeon; if (!Global.LFGMgr.AllQueued(check)) { Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) Group MATCH but can't create proposal!", strGuids); SetCompatibles(strGuids, LfgCompatibility.BadStates); return(LfgCompatibility.BadStates); } // Create a new proposal proposal.cancelTime = Time.UnixTime + SharedConst.LFGTimeProposal; proposal.state = LfgProposalState.Initiating; proposal.leader = ObjectGuid.Empty; proposal.dungeonId = proposalDungeons.SelectRandom(); bool leader = false; foreach (var rolePair in proposalRoles) { // Assing new leader if (rolePair.Value.HasAnyFlag(LfgRoles.Leader)) { if (!leader || proposal.leader.IsEmpty() || Convert.ToBoolean(RandomHelper.IRand(0, 1))) { proposal.leader = rolePair.Key; } leader = true; } else if (!leader && (proposal.leader.IsEmpty() || Convert.ToBoolean(RandomHelper.IRand(0, 1)))) { proposal.leader = rolePair.Key; } // Assing player data and roles LfgProposalPlayer data = new LfgProposalPlayer(); data.role = rolePair.Value; data.group = proposalGroups.LookupByKey(rolePair.Key); if (!proposal.isNew && !data.group.IsEmpty() && data.group == proposal.group) // Player from existing group, autoaccept { data.accept = LfgAnswer.Agree; } proposal.players[rolePair.Key] = data; } // Mark proposal members as not queued (but not remove queue data) foreach (var guid in proposal.queues) { RemoveFromNewQueue(guid); RemoveFromCurrentQueue(guid); } Global.LFGMgr.AddProposal(proposal); Log.outDebug(LogFilter.Lfg, "CheckCompatibility: ({0}) MATCH! Group formed", strGuids); SetCompatibles(strGuids, LfgCompatibility.Match); return(LfgCompatibility.Match); }
private static bool CheckAndPutInNearbyGym(FortData gym, Client client) { if (!GlobalVars.Gyms.Farm) { return(false); } if (gymsVisited.IndexOf(gym.Id) > -1) { return(false); } Logger.Debug("(Gym) - Reviving pokemons."); ReviveAndCurePokemons(client); var pokemons = (client.Inventory.GetPokemons()).ToList(); RandomHelper.RandomSleep(900); var buddyID = 0UL; if (client.Player.PlayerResponse.PlayerData.BuddyPokemon != null) { buddyID = client.Player.PlayerResponse.PlayerData.BuddyPokemon.Id; } PokemonData pokemon = getPokeToPut(client, buddyID, gym.GuardPokemonCp); if (pokemon == null) { Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - There are no pokemons to assign."); return(false); } Logger.Debug("(Gym) - Pokemon to deploy: " + strPokemon(pokemon)); var gymDetails = client.Fort.GetGymDetails(gym.Id, gym.Latitude, gym.Longitude); Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Team: " + GetTeamName(gym.OwnedByTeam) + "."); if (gymDetails.GymState.Memberships != null && gymDetails.GymState.Memberships.Count > 0) { var level = GetGymLevel(gym.GymPoints); var nextLevel = GetLevelPoints(level + 1); Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Members: " + gymDetails.GymState.Memberships.Count + $". Level: {level} ( {gym.GymPoints }/{nextLevel})"); } Logger.Debug("(Gym) - Name: " + gymDetails.Name); Logger.Debug("(Gym) - Description: " + gymDetails.Description); if (gym.OwnedByTeam == TeamColor.Neutral) { RandomHelper.RandomSleep(250); putInGym(client, gym, pokemon, pokemons); } else if ((gym.OwnedByTeam == client.Player.PlayerResponse.PlayerData.Team)) { RandomHelper.RandomSleep(250); if (gymDetails.GymState.Memberships.Count < GetGymLevel(gym.GymPoints)) { Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - There is a free space"); putInGym(client, gym, pokemon, pokemons); } else if (GlobalVars.Gyms.Attack && gymDetails.GymState.Memberships.Count <= GlobalVars.Gyms.NumDefenders) { if (gym.GymPoints >= GlobalVars.Gyms.MaxTrainingXP) { Logger.Warning($"(Gym) - Maximum Gym level to train ({GlobalVars.Gyms.MaxTrainingXP}) reached."); AddVisited(gym.Id, 600000); return(true); } restoreWalkingAfterLogic = !GlobalVars.PauseTheWalking; GlobalVars.PauseTheWalking = true; Logger.Debug("(Gym) - Stop walking "); var defenders = gymDetails.GymState.Memberships.Select(x => x.PokemonData); var defender = defenders.FirstOrDefault(); Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Defender: " + strPokemon(defender)); var pokeAttackers = getPokeAttackers(pokemons, defender); if (pokeAttackers.Count() < 6) { Logger.Warning("(Gym) - There are not enouth pokemons to train"); return(false); } Logger.ColoredConsoleWrite(gymColorLog, "(Gym) Let's go to train"); Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Selected pokemons to train:"); ShowPokemons(pokeAttackers); var attResp = AttackGym(gym, client, pokeAttackers, defender.Id, gymDetails.GymState.Memberships.Count, buddyID); } else { Logger.Warning("(Gym) - There is no free space in the gym"); AddVisited(gym.Id, 600000); } } else { Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - This gym is not from your team."); if (!GlobalVars.Gyms.Attack) { Logger.Debug("Attack is disabled"); AddVisited(gym.Id, 600000); return(false); } if (gymDetails.GymState.Memberships.Count >= 1 && gymDetails.GymState.Memberships.Count <= GlobalVars.Gyms.NumDefenders) { restoreWalkingAfterLogic = !GlobalVars.PauseTheWalking; GlobalVars.PauseTheWalking = true; Logger.Debug("(Gym) - Stop walking "); var defenders = gymDetails.GymState.Memberships.Select(x => x.PokemonData); var defender = defenders.FirstOrDefault(); Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Defender: " + strPokemon(defender)); var pokeAttackers = getPokeAttackers(pokemons, defender); if (pokeAttackers.Count() < 6) { Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - There are not enouth pokemons to fight"); return(false); } Logger.ColoredConsoleWrite(gymColorLog, "(Gym) Let's go to fight"); Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Selected Atackers:"); ShowPokemons(pokeAttackers); var attResp = AttackGym(gym, client, pokeAttackers, defender.Id, gymDetails.GymState.Memberships.Count, buddyID); } else { AddVisited(gym.Id, 600000); } } return(true); }
private async Task BuildForInternalAsync(Tenant tenant) { //Create Organization Units var organizationUnits = new List <OrganizationUnit>(); var producing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Producing"); var researchAndDevelopment = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Research & Development", producing); var ivrProducts = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "IVR Related Products", researchAndDevelopment); var voiceTech = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Voice Technologies", researchAndDevelopment); var inhouseProjects = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Inhouse Projects", researchAndDevelopment); var qualityManagement = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Quality Management", producing); var testing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Testing", producing); var selling = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Selling"); var marketing = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Marketing", selling); var sales = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Sales", selling); var custRelations = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Customer Relations", selling); var supporting = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Supporting"); var buying = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Buying", supporting); var humanResources = await CreateAndSaveOrganizationUnit(organizationUnits, tenant, "Human Resources", supporting); //Create users var users = _randomUserGenerator.GetRandomUsers(RandomHelper.GetRandom(12, 26), tenant.Id); foreach (var user in users) { //Create the user await _userManager.CreateAsync(user); await CurrentUnitOfWork.SaveChangesAsync(); //Add to roles await _userManager.AddToRoleAsync(user, StaticRoleNames.Tenants.User); //Add to OUs var randomOus = RandomHelper.GenerateRandomizedList(organizationUnits).Take(RandomHelper.GetRandom(0, 3)); foreach (var ou in randomOus) { await _userManager.AddToOrganizationUnitAsync(user, ou); } //Set profile picture if (RandomHelper.GetRandom(100) < 70) //A user will have a profile picture in 70% probability. { await SetRandomProfilePictureAsync(user); } } //Set a picture to admin! var admin = await _userManager.FindByNameAsync(AbpUserBase.AdminUserName); await SetRandomProfilePictureAsync(admin); //Create Friendships var friends = RandomHelper.GenerateRandomizedList(users).Take(3).ToList(); foreach (var friend in friends) { await _friendshipManager.CreateFriendshipAsync( new Friendship( admin.ToUserIdentifier(), friend.ToUserIdentifier(), tenant.TenancyName, friend.UserName, friend.ProfilePictureId, FriendshipState.Accepted) ); await _friendshipManager.CreateFriendshipAsync( new Friendship( friend.ToUserIdentifier(), admin.ToUserIdentifier(), tenant.TenancyName, admin.UserName, admin.ProfilePictureId, FriendshipState.Accepted) ); } //Create chat message var friendWithMessage = RandomHelper.GenerateRandomizedList(friends).First(); var sharedMessageId = Guid.NewGuid(); _chatMessageRepository.InsertAndGetId( new ChatMessage( friendWithMessage.ToUserIdentifier(), admin.ToUserIdentifier(), ChatSide.Sender, L("Demo_SampleChatMessage"), ChatMessageReadState.Read, sharedMessageId, ChatMessageReadState.Unread ) ); _chatMessageRepository.InsertAndGetId( new ChatMessage( admin.ToUserIdentifier(), friendWithMessage.ToUserIdentifier(), ChatSide.Receiver, L("Demo_SampleChatMessage"), ChatMessageReadState.Unread, sharedMessageId, ChatMessageReadState.Read ) ); }
private static AttackGymResponse AttackGym(FortData gym, Client client, IEnumerable <PokemonData> pokeAttackers, ulong defenderId, int numDefenders, ulong buddyPokemonId) { var pokeAttackersIds = pokeAttackers.Select(x => x.Id); var moveSettings = GetMoveSettings(client); GetGymDetailsResponse gymDetails = null; StartGymBattleResponse resp = null; // Sometimes we get a null from startgymBattle so we try to start battle 3 times var numTries = 1; var startFailed = true; const int secondsToWait = 2; while (startFailed && numTries < 4) { gymDetails = client.Fort.GetGymDetails(gym.Id, gym.Latitude, gym.Longitude); RandomHelper.RandomSleep(secondsToWait * 1000); resp = StartGymBattle(client, gym.Id, defenderId, pokeAttackersIds); startFailed = false; if (resp == null) { Logger.Warning($"(Gym) - Try to Attack number {numTries} failed."); Logger.Debug("(Gym) - Response to start battle was null."); startFailed = true; } else { if (resp.BattleLog == null) { Logger.Warning($"(Gym) - Try to Attack number {numTries} failed."); Logger.Debug("(Gym) - BatlleLog to start battle was null"); startFailed = true; } } if (startFailed) { Logger.Debug($"(Gym) - Trying again after {secondsToWait} seconds"); } numTries++; } if (startFailed) { return(null); } if (resp.BattleLog.State == BattleState.Active) { Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Battle Started"); RandomHelper.RandomSleep(2000); var battleActions = new List <BattleAction>(); var lastRetrievedAction = new BattleAction(); var battleStartMs = resp.BattleLog.BattleStartTimestampMs; var attResp = client.Fort.AttackGym(gym.Id, resp.BattleId, battleActions, lastRetrievedAction); var inBattle = (attResp.Result == AttackGymResponse.Types.Result.Success); inBattle = inBattle && (attResp.BattleLog.State == BattleState.Active); var count = 1; var energy = 0; var numVictories = 0; Logger.Debug("attResp: " + attResp); while (inBattle) { var timeMs = attResp.BattleLog.ServerMs; var move1Settings = moveSettings.FirstOrDefault(x => x.MoveSettings.MovementId == attResp.ActiveAttacker.PokemonData.Move1).MoveSettings; var move2Settings = moveSettings.FirstOrDefault(x => x.MoveSettings.MovementId == attResp.ActiveAttacker.PokemonData.Move2).MoveSettings; battleActions = new List <BattleAction>(); var baseAction = new BattleAction(); baseAction.ActionStartMs = timeMs + RandomNumbers.Next(110, 170); baseAction.TargetIndex = -1; if (attResp.ActiveDefender != null) { baseAction.TargetPokemonId = attResp.ActiveDefender.PokemonData.Id; } if (attResp.ActiveAttacker.PokemonData.Stamina > 0) { baseAction.ActivePokemonId = attResp.ActiveAttacker.PokemonData.Id; } // One each ten times we try to evade attack if (RandomNumbers.Next(1, 10) == 1) { var dodgeAction = new BattleAction(); dodgeAction.ActionStartMs = baseAction.ActionStartMs; dodgeAction.TargetIndex = baseAction.TargetIndex; dodgeAction.TargetPokemonId = baseAction.TargetPokemonId; dodgeAction.ActivePokemonId = baseAction.ActivePokemonId; dodgeAction.Type = BattleActionType.ActionDodge; dodgeAction.DurationMs = 500; battleActions.Add(dodgeAction); Logger.Debug("Dodge Action Added"); baseAction.ActionStartMs = dodgeAction.ActionStartMs + dodgeAction.DurationMs; } if (energy >= Math.Abs(move2Settings.EnergyDelta)) { var specialAttack = new BattleAction(); specialAttack.ActionStartMs = baseAction.ActionStartMs; specialAttack.TargetIndex = baseAction.TargetIndex; specialAttack.TargetPokemonId = baseAction.TargetPokemonId; specialAttack.ActivePokemonId = baseAction.ActivePokemonId; specialAttack.Type = BattleActionType.ActionSpecialAttack; specialAttack.DurationMs = move2Settings.DurationMs; specialAttack.DamageWindowsStartTimestampMs = specialAttack.ActionStartMs + move2Settings.DamageWindowStartMs; specialAttack.DamageWindowsEndTimestampMs = specialAttack.ActionStartMs + move2Settings.DamageWindowEndMs; specialAttack.EnergyDelta = move2Settings.EnergyDelta; battleActions.Add(specialAttack); Logger.Debug("Special Attack Added"); baseAction.ActionStartMs = specialAttack.ActionStartMs + specialAttack.DurationMs; } else { // One each nine times we do not attack if (RandomNumbers.Next(1, 9) != 1) { var normalAttack = new BattleAction(); normalAttack.ActionStartMs = baseAction.ActionStartMs; normalAttack.TargetIndex = baseAction.TargetIndex; normalAttack.TargetPokemonId = baseAction.TargetPokemonId; normalAttack.ActivePokemonId = baseAction.ActivePokemonId; normalAttack.Type = BattleActionType.ActionAttack; normalAttack.DurationMs = baseAction.DurationMs; normalAttack.DamageWindowsStartTimestampMs = normalAttack.ActionStartMs + move1Settings.DamageWindowStartMs; normalAttack.DamageWindowsEndTimestampMs = normalAttack.ActionStartMs + move1Settings.DamageWindowEndMs; normalAttack.EnergyDelta = move1Settings.EnergyDelta; battleActions.Add(normalAttack); Logger.Debug("Normal Attack Added"); baseAction.ActionStartMs = normalAttack.ActionStartMs + normalAttack.DurationMs; } } switch (GlobalVars.Gyms.Testing) { case "Empty Action": lastRetrievedAction = new BattleAction(); break; case "First Action": lastRetrievedAction = attResp.BattleLog.BattleActions.FirstOrDefault(x => x.ActivePokemonId != attResp.ActiveAttacker.PokemonData.Id); //new BattleAction(); break; default: lastRetrievedAction = attResp.BattleLog.BattleActions.LastOrDefault(x => x.ActivePokemonId != attResp.ActiveAttacker.PokemonData.Id); //new BattleAction(); break; } var str = string.Join(",", battleActions); Logger.Debug("(Gym) - battleActions: " + str); attResp = client.Fort.AttackGym(gym.Id, resp.BattleId, battleActions, lastRetrievedAction); Logger.Debug("attResp: " + attResp); Logger.Debug("attResp BattleActions: "); ShowBattleActions(attResp.BattleLog.BattleActions); inBattle = (attResp.Result == AttackGymResponse.Types.Result.Success); if (inBattle) { inBattle = (attResp.BattleLog.State == BattleState.Active); if (attResp.BattleLog.State == BattleState.Victory) { numVictories++; if (GlobalVars.Gyms.Testing == "Restart Battle After of Victory") { //inBattle = (numVictories < gymDetails.GymState.Memberships.Count); if (numVictories < gymDetails.GymState.Memberships.Count) { var next = GetNextDefender(attResp.BattleLog.BattleActions); //gymDetails.GymState.Memberships[numVictories]; resp = StartGymBattle(client, gym.Id, (ulong)next, pokeAttackersIds); RandomHelper.RandomSleep(1000); } } } if (attResp.ActiveAttacker != null) { energy = attResp.ActiveAttacker.CurrentEnergy; var health = attResp.ActiveAttacker.CurrentHealth; var activeAttacker = attResp.ActiveAttacker.PokemonData.PokemonId; Logger.Debug($"(Gym) - Attacker: {activeAttacker} Energy={energy}, Health={health}"); } if (attResp.ActiveDefender != null) { var energyDef = attResp.ActiveDefender.CurrentEnergy; var health = attResp.ActiveDefender.CurrentHealth; var activeDefender = attResp.ActiveDefender.PokemonData.PokemonId; Logger.Debug($"(Gym) - Defender: {activeDefender} Energy={energyDef}, Health={health}"); } count++; // Wait until all attack are done. but not more than 1.5 seconds. var waitTime = (int)(baseAction.ActionStartMs - attResp.BattleLog.ServerMs); if (waitTime < 0) { waitTime = 0; } else if (waitTime > 1200) { waitTime = 1200; } RandomHelper.RandomSleep(waitTime, waitTime + 100); } } Logger.ColoredConsoleWrite(gymColorLog, $"(Gym) - Battle Finished in {count} Rounds."); if (attResp.Result == AttackGymResponse.Types.Result.Success) { switch (attResp.BattleLog.State) { case BattleState.Defeated: Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - We have lost"); if (numDefenders > 1) { AddVisited(gym.Id, 3600000); } break; case BattleState.Victory: Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - We have won"); var nextDefenderID = -1L; foreach (var element in attResp.BattleLog.BattleActions) { if (element.BattleResults != null) { Logger.Info("(Gym) - Gym points: " + element.BattleResults.GymPointsDelta); Logger.Info("(Gym) - Experience Awarded: " + element.BattleResults.PlayerExperienceAwarded); Logger.Debug("(Gym) - Next Pokemon: " + element.BattleResults.NextDefenderPokemonId); if (element.BattleResults.NextDefenderPokemonId != -1) { nextDefenderID = element.BattleResults.NextDefenderPokemonId; } } } if (numDefenders > 1) { Logger.Debug("(Gym) - Leaving Battle"); var times = 3; do { attResp = LeaveBattle(gym, client, resp, attResp, lastRetrievedAction, nextDefenderID); times--; } while (attResp.Result != AttackGymResponse.Types.Result.Success && times > 0); RandomHelper.RandomSleep(800); } else { ReviveAndCurePokemons(client); var pokemons = (client.Inventory.GetPokemons()).ToList(); RandomHelper.RandomSleep(400); gymDetails = client.Fort.GetGymDetails(gym.Id, gym.Latitude, gym.Longitude); Logger.Debug("(Gym) - Gym Details: " + gymDetails); if (gymDetails.GymState.Memberships.Count < 1) { putInGym(client, gym, getPokeToPut(client, buddyPokemonId, gym.GuardPokemonCp), pokemons); } } break; case BattleState.TimedOut: Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Timed Out"); AddVisited(gym.Id, 1800000); break; } } else { Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Battle Failed: " + attResp.Result); } return(attResp); } return(null); }
// 解决103错误码 private bool TestLogin() { Logger.Instance.Debug("开始向服务器发送测试连接请求"); var result = Client.GetStringAsync(ApiUrl.TestLogin, Vfwebqq, ClientId, Psessionid, RandomHelper.GetRandomDouble()); result.Wait(); return(result.IsCompleted && JObject.Parse(result.Result)["retcode"].Value <int?>() == 0); }
public static StartGymBattleResponse StartGymBattle(Client client, string gymId, ulong defendingPokemonId, IEnumerable <ulong> attackingPokemonIds) { StartGymBattleResponse resp = null; var numTries = 3; var startOk = false; do { try { resp = client.Fort.StartGymBattle(gymId, defendingPokemonId, attackingPokemonIds).Result; if (resp == null) { Logger.Debug("(Gym) - Response to start battle was null."); } else { if (resp.BattleLog == null) { Logger.Debug("(Gym) - BatlleLog to start battle was null"); } else { startOk = true; Logger.Debug("StartGymBattle Response:" + resp); } } } catch (Exception ex1) { Logger.ExceptionInfo("StartGymBattle: " + ex1); RandomHelper.RandomSleep(5000); if (GlobalVars.Gyms.Testing == "Relogin") { client.Login.DoLogin().Wait(); } else if (GlobalVars.Gyms.Testing == "GetPlayer") { client.Player.GetPlayer(); RandomHelper.RandomSleep(3000); } else if (GlobalVars.Gyms.Testing == "Wait 2 minutes catching pokemons") { if (GlobalVars.CatchPokemon) { Logger.Info("Trying to catch pokemons until next attack"); } // 0.00001 = 1 meters // http://www.um.es/geograf/sigmur/temariohtml/node6_mn.html //http://gizmodo.com/how-precise-is-one-degree-of-longitude-or-latitude-1631241162 var gymloc = new GeoCoordinate(client.CurrentLongitude, client.CurrentLatitude, client.CurrentAltitude); for (var times = 1; times < 5; times++) { var rnd = RandomHelper.GetLongRandom(8, 9) * 0.00001; Logger.Debug("going to 8 meters far of gym"); LocationUtils.updatePlayerLocation(client, gymloc.Longitude + rnd, gymloc.Latitude, gymloc.Altitude); RandomHelper.RandomSleep(10000); CatchingLogic.Execute(); rnd = RandomHelper.GetLongRandom(8, 9) * 0.00001; Logger.Debug("going to 8 meters far of gym"); LocationUtils.updatePlayerLocation(client, gymloc.Longitude + rnd, gymloc.Latitude, gymloc.Altitude); RandomHelper.RandomSleep(10000); CatchingLogic.Execute(); Logger.Debug("returning to gym location"); // go back LocationUtils.updatePlayerLocation(client, gymloc.Longitude, gymloc.Latitude, gymloc.Altitude); RandomHelper.RandomSleep(10000); CatchingLogic.Execute(); } RandomHelper.RandomSleep(2000); } else { RandomHelper.RandomSleep(115000); client.Login.DoLogin().Wait(); } } numTries--; } while (!startOk && numTries > 0); return(resp); }
public static void ClientAddHitSparks( IReadOnlyWeaponHitSparksPreset hitSparksPreset, WeaponHitData hitData, IWorldObject hitWorldObject, IProtoWorldObject protoWorldObject, Vector2D worldObjectPosition, int projectilesCount, ObjectMaterial objectMaterial, bool randomizeHitPointOffset, bool randomRotation, double?rotationAngleRad, DrawOrder drawOrder, double scale = 1.0, double animationFrameDuration = 2 / 60.0) { var sceneObject = Api.Client.Scene.CreateSceneObject("Temp_HitSparks"); sceneObject.Position = worldObjectPosition; var hitPoint = hitData.HitPoint.ToVector2D(); var sparksEntry = hitSparksPreset.GetForMaterial(objectMaterial); if (!hitData.IsCliffsHit && randomizeHitPointOffset) { // move hitpoint a bit closer to the center of the object hitPoint = WeaponSystem.SharedOffsetHitWorldPositionCloserToObjectCenter( hitWorldObject, protoWorldObject, hitPoint, isRangedWeapon: randomizeHitPointOffset); } if (projectilesCount == 1 && randomizeHitPointOffset && sparksEntry.AllowRandomizedHitPointOffset) { // randomize hitpoint a bit by adding a little random offset var maxOffsetDistance = 0.2; var range = maxOffsetDistance * RandomHelper.NextDouble(); var angleRad = 2 * Math.PI * RandomHelper.NextDouble(); var randomOffset = new Vector2D(range * Math.Cos(angleRad), range * Math.Sin(angleRad)); hitPoint += randomOffset; } var componentSpriteRender = Api.Client.Rendering.CreateSpriteRenderer( sceneObject, positionOffset: hitPoint, spritePivotPoint: (0.5, sparksEntry.PivotY), drawOrder: drawOrder); componentSpriteRender.DrawOrderOffsetY = -hitPoint.Y; componentSpriteRender.Scale = (float)scale * Math.Pow(1.0 / projectilesCount, 0.35); if (sparksEntry.UseScreenBlending) { componentSpriteRender.BlendMode = BlendMode.Screen; } if (randomRotation) { componentSpriteRender.RotationAngleRad = (float)(RandomHelper.NextDouble() * 2 * Math.PI); } else if (rotationAngleRad.HasValue) { componentSpriteRender.RotationAngleRad = (float)(rotationAngleRad.Value - Math.PI / 2); } var componentAnimator = sceneObject.AddComponent <ClientComponentSpriteSheetAnimator>(); var hitSparksEntry = sparksEntry; componentAnimator.Setup( componentSpriteRender, hitSparksEntry.SpriteSheetAnimationFrames, frameDurationSeconds: animationFrameDuration, isLooped: false); var totalAnimationDuration = animationFrameDuration * componentAnimator.FramesCount; var totalDurationWithLight = 0.15 + totalAnimationDuration; if (hitSparksEntry.LightColor.HasValue) { // create light spot (even for melee weapons) var lightSource = ClientLighting.CreateLightSourceSpot( sceneObject, color: hitSparksEntry.LightColor.Value, spritePivotPoint: (0.5, 0.5), size: 7, // we don't want to display nickname/healthbar for the firing character, it's too quick anyway logicalSize: 0, positionOffset: hitPoint); ClientComponentOneShotLightAnimation.Setup(lightSource, totalDurationWithLight); } componentSpriteRender.Destroy(totalAnimationDuration); componentAnimator.Destroy(totalAnimationDuration); sceneObject.Destroy(totalDurationWithLight); }
private static void SendContinuousErrors(int delay, CancellationToken token, bool randomizeDates = false, int maxErrors = Int32.MaxValue, int uniqueCount = 1, bool randomizeCritical = true) { _sendingContinuous = true; Console.WriteLine(); Console.WriteLine("Press 's' to stop sending."); int errorCount = 0; if (uniqueCount <= 0) { uniqueCount = 1; } var errorCodeList = new List <int>(); for (int i = 0; i < uniqueCount; i++) { errorCodeList.Add(_random.Next()); } Task.Factory.StartNew(delegate { while (errorCount < maxErrors) { if (token.IsCancellationRequested) { _sendingContinuous = false; break; } SendError(randomizeDates, errorCodeList.Random(), randomizeCritical ? RandomHelper.GetBool() : false, writeToConsole: false); errorCount++; Console.SetCursorPosition(0, 13); Console.WriteLine("Sent {0} errors.", errorCount); Trace.WriteLine(String.Format("Sent {0} errors.", errorCount)); Thread.Sleep(delay); } }, token); }
public void IndexFiles(FileInfo[] imageFiles, System.ComponentModel.BackgroundWorker IndexBgWorker, Action<string> logWriter, LocateSettings locateSetting = null) { //For Time Profilling long extractingTime, kMeanTime = 0, calcBagOfVisualTime = 0; Stopwatch sw1; SimpleSurfSift.LoCATe descriptorExtractor = new SimpleSurfSift.LoCATe(); sw1 = Stopwatch.StartNew(); logWriter("Index started, extracting Descriptors..."); List<double[]> ListofDescriptorsForCookBook = new List<double[]>(); List<LoCATeRecord> ListOfAllImageDescriptors = new List<LoCATeRecord>(); int totalFileCount = imageFiles.Length; if (totalFileCount == 0) { logWriter("No files to index"); return; }; for (int i = 0; i < totalFileCount; i++) { var fi = imageFiles[i]; using (Bitmap observerImage = (Bitmap)Image.FromFile(fi.FullName)) { List<double[]> locateDescriptors = descriptorExtractor.extract(observerImage, "SURF"); ListOfAllImageDescriptors.Add(new LoCATeRecord { Id = i, ImageName = fi.Name, ImagePath = fi.FullName, LoCATeDescriptors = locateDescriptors }); if (locateSetting.IsCodeBookNeedToBeCreated) { if (locateDescriptors.Count > 4) { RandomHelper randNumGenerator = new RandomHelper(); List<int> randIndexes = randNumGenerator.GetRandomNumberInRange(0, locateDescriptors.Count, 10d); foreach (int index in randIndexes) { ListofDescriptorsForCookBook.Add(locateDescriptors[index]); } } else { Debug.WriteLine(fi.Name + " skip from index, because it didn't have significant feature"); } } } IndexBgWorker.ReportProgress(i); } sw1.Stop(); extractingTime = Convert.ToInt32(sw1.Elapsed.TotalSeconds); double[][] codeBook = null; if (locateSetting.IsCodeBookNeedToBeCreated) { logWriter("Indexing, Calculating Mean..."); sw1.Reset(); sw1.Start(); KMeans kMeans = new KMeans(locateSetting.SizeOfCodeBook); kMeans.Compute(ListofDescriptorsForCookBook.ToArray()); codeBook = kMeans.Clusters.Centroids; //------------Save CookBook string fullFileName = locateSetting.CodeBookFullPath; if (File.Exists(fullFileName)) File.Delete(fullFileName); using (FileStream fs = new FileStream(fullFileName, FileMode.Create, FileAccess.Write, FileShare.None)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(fs, codeBook); fs.Close(); } sw1.Stop(); kMeanTime = Convert.ToInt32(sw1.Elapsed.TotalSeconds); } else { string fullFileName = locateSetting.CodeBookFullPath; if (!File.Exists(fullFileName)) { string msg = string.Format("Couldn't find {0}, Please Index before querying with Locate", fullFileName); throw new InvalidOperationException(msg); } using (FileStream fs = new FileStream(fullFileName, FileMode.Open, FileAccess.Read, FileShare.None)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); codeBook = (double[][])bf.Deserialize(fs); fs.Close(); } } logWriter("Indexing, Calculating Bag of Visual Words..."); sw1.Reset(); sw1.Start(); List<LoCaTeBoWRecord> ListOfImageVisualBagOfWorks = new List<LoCaTeBoWRecord>(); for (int i = 0; i < ListOfAllImageDescriptors.Count; i++) { double[] visualWordForImage = createVisualWord(ListOfAllImageDescriptors[i].LoCATeDescriptors, codeBook); LoCaTeBoWRecord rec = new LoCaTeBoWRecord { Id = ListOfAllImageDescriptors[i].Id, ImageName = ListOfAllImageDescriptors[i].ImageName, ImagePath = ListOfAllImageDescriptors[i].ImagePath, VisaulWord = visualWordForImage }; ListOfImageVisualBagOfWorks.Add(rec); IndexBgWorker.ReportProgress(i); } logWriter("Indexing, Calculating ltcData..."); int[] histogramSumOfAllVisualWords = null; //------------Creating sum histogram of all words double[][] AllDatas = ListOfImageVisualBagOfWorks.Select(des => des.VisaulWord).ToArray(); histogramSumOfAllVisualWords = createIndex((double[][])(AllDatas)); //------------Creating Image Records Data LoCaTeDataSet locateDS = new LoCaTeDataSet { AllImageRecordSet = ListOfImageVisualBagOfWorks, HistogramSumOfAllVisualWords = histogramSumOfAllVisualWords }; logWriter("Indexing, Saving Image Data..."); //------------Save CookBook string ImageRecordName = Path.Combine(DirectoryHelper.SaveDirectoryPath, "LoCATeImageRecords.bin"); if (File.Exists(ImageRecordName)) File.Delete(ImageRecordName); using (FileStream fs = new FileStream(ImageRecordName, FileMode.Create, FileAccess.Write, FileShare.None)) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(fs, locateDS); fs.Close(); } sw1.Stop(); calcBagOfVisualTime = Convert.ToInt32(sw1.Elapsed.TotalSeconds); logWriter(string.Format("Extracting: {0} sec, KMeanTime: {1} sec, CalcBagOfVisalTime: {2} sec", extractingTime, kMeanTime, calcBagOfVisualTime)); }
public Vector2 GeneratePosition() { return(RandomHelper.GetRandom(center - r, center + r)); }
static void Random_Generator_Test() { RandomHelper random = new RandomHelper(); for (int i = 1; i <= 100000; i++) { Loger.Info(random.Number(4, false)); } //for (int i = 1; i <= 100000; i++) //{ // Loger.Info(String.Join("", random.GenerateNumber(4))); //} Console.WriteLine("生成结束"); }
private async Task ExecuteFarmingPokestopsAndPokemons(Client client) { var distanceFromStart = LocationUtils.CalculateDistanceInMeters(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude, _client.CurrentLat, _client.CurrentLng); if (_clientSettings.MaxWalkingRadiusInMeters != 0 && distanceFromStart > _clientSettings.MaxWalkingRadiusInMeters) { Logger.ColoredConsoleWrite(ConsoleColor.Green, "Youre outside of the defined Max Walking Radius. Walking back!"); var update = await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons); var start = await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons); } Resources.OutPutWalking = true; var mapObjects = await _client.GetMapObjects(); //var pokeStops = mapObjects.MapCells.SelectMany(i => i.Forts).Where(i => i.Type == FortType.Checkpoint && i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime()); var pokeStops = _navigation.pathByNearestNeighbour( mapObjects.MapCells.SelectMany(i => i.Forts) .Where( i => i.Type == FortType.Checkpoint && i.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime()) .OrderBy( i => LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, i.Latitude, i.Longitude)).ToArray(), _clientSettings.WalkingSpeedInKilometerPerHour); if (_clientSettings.MaxWalkingRadiusInMeters != 0) { pokeStops = pokeStops.Where(i => LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, i.Latitude, i.Longitude) <= _clientSettings.MaxWalkingRadiusInMeters).ToArray(); if (pokeStops.Count() == 0) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "We cant find any PokeStops in a range of " + _clientSettings.MaxWalkingRadiusInMeters + "m!"); await ExecuteCatchAllNearbyPokemons(); } } if (pokeStops.Count() == 0) { Logger.ColoredConsoleWrite(ConsoleColor.Red, "We cant find any PokeStops, which are unused! Probably Server unstable, or you visted them all. Retrying.."); await ExecuteCatchAllNearbyPokemons(); } else { Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "We found " + pokeStops.Count() + " PokeStops near."); } foreach (var pokeStop in pokeStops) { // replace this true with settings variable!! await UseIncense(); await ExecuteCatchAllNearbyPokemons(); if (count >= 3) { count = 0; await StatsLog(client); if (_clientSettings.EvolvePokemonsIfEnoughCandy) { await EvolveAllPokemonWithEnoughCandy(); } await TransferDuplicatePokemon(_clientSettings.keepPokemonsThatCanEvolve); await RecycleItems(); } if (_clientSettings.pokevision) { foreach (spottedPoke p in await _pokevision.GetNearPokemons(_client.CurrentLat, _client.CurrentLng)) { var dist = LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, p._lat, p._lng); Logger.ColoredConsoleWrite(ConsoleColor.Magenta, $"PokeVision: A {StringUtils.getPokemonNameByLanguage(_clientSettings, p._pokeId)} in {dist:0.##}m distance. Trying to catch."); var upd = await _navigation.HumanLikeWalking(new GeoCoordinate(p._lat, p._lng), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons); } } var distance = LocationUtils.CalculateDistanceInMeters(_client.CurrentLat, _client.CurrentLng, pokeStop.Latitude, pokeStop.Longitude); var fortInfo = await _client.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); if (fortInfo == null) { continue; } Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Next Pokestop: {fortInfo.Name} in {distance:0.##}m distance."); var update = await _navigation.HumanLikeWalking(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons); ////var fortInfo = await client.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); var fortSearch = await _client.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); count++; if (fortSearch.ExperienceAwarded > 0) { failed_softban = 0; _botStats.addExperience(fortSearch.ExperienceAwarded); var egg = ""; if (fortSearch.PokemonDataEgg != null) { egg = "Egg " + fortSearch.PokemonDataEgg.EggKmWalkedTarget; } else { egg = "/"; } var i = ""; if (StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded) != "") { i = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded); } else { i = "/"; } Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Farmed XP: {fortSearch.ExperienceAwarded}, Gems: { fortSearch.GemsAwarded}, Eggs: {egg} Items: {i}", LogLevel.Info); } else { failed_softban++; if (failed_softban >= 6) { Logger.Error("Detected a Softban. Trying to use our Special 1337 Unban Methode."); for (int i = 0; i < 60; i++) { var unban = await client.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); if (unban.ExperienceAwarded > 0) { break; } } failed_softban = 0; Logger.ColoredConsoleWrite(ConsoleColor.Green, "Probably unbanned you."); } } await RandomHelper.RandomDelay(50, 200); } if (_clientSettings.WalkBackToDefaultLocation) { Logger.ColoredConsoleWrite(ConsoleColor.Green, "Walking back to Default Location."); await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons); } }