public override DefinitionBase GenerateRandomDefinition(Action <DefinitionBase> action)
        {
            return(WithEmptyDefinition(def =>
            {
                def.AllowPrint = Rnd.Bool();
                def.AllowScript = Rnd.Bool();
                def.AllowWriteCopy = Rnd.Bool();

                def.DisableDocumentBrowserView = Rnd.Bool();
                def.DocumentAccessExpireDays = Rnd.Int(300);
                def.DocumentLibraryProtectionExpireDate = Rnd.Date();

                def.EnableDocumentAccessExpire = Rnd.Bool();
                def.EnableDocumentBrowserPublishingView = Rnd.Bool();
                def.EnableGroupProtection = Rnd.Bool();
                def.EnableLicenseCacheExpire = Rnd.Bool();

                def.GroupName = Rnd.UserEmail();
                def.LicenseCacheExpireDays = Rnd.Int(255);

                def.PolicyDescription = Rnd.String();
                def.PolicyTitle = Rnd.String();
            }));
        }
        public void SmallCardinalityRepeatedInsert()
        {
            var       hll         = new HyperLogLogPlus(14, 25);
            const int count       = 15000;
            const int maxAttempts = 200;

            for (var i = 0; i < count; i++)
            {
                var n = Rnd.Next(maxAttempts) + 1;
                for (var j = 0; j < n; j++)
                {
                    hll.OfferHashed(Hash64("i" + i));
                }
            }
            long       estimate            = hll.Cardinality();
            double     se                  = count * (1.04 / Math.Sqrt(Math.Pow(2, 14)));
            const long expectedCardinality = count;

            Console.WriteLine("Expect estimate: {0} is between {1} and {2}", estimate, expectedCardinality - (3 * se),
                              expectedCardinality + (3 * se));

            Assert.That(estimate, Is.GreaterThanOrEqualTo(expectedCardinality - (3 * se)));
            Assert.That(estimate, Is.LessThanOrEqualTo(expectedCardinality + (3 * se)));
        }
示例#3
0
        public void CanDeploy_DocumentLibrary_With_SiteCollectionToken_DocumentTemplateUrl()
        {
            var templateFileName = Rnd.TxtFileName();

            var webModel = SPMeta2Model
                           .NewWebModel(web =>
            {
                var randomList = ModelGeneratorService.GetRandomDefinition <ListDefinition>(def =>
                {
                    def.TemplateType = BuiltInListTemplateTypeId.DocumentLibrary;
                });

                // add first to provision, add a module
                web.AddList(randomList, list =>
                {
                    list.AddHostFolder(BuiltInFolderDefinitions.Forms, folder =>
                    {
                        folder.AddModuleFile(new ModuleFileDefinition
                        {
                            FileName = templateFileName,
                            Content  = Encoding.UTF8.GetBytes(Rnd.String())
                        });
                    });
                });

                // add a clone second time with the template
                var listWithDocumentTemplate = randomList.Inherit();
#pragma warning disable 618
                listWithDocumentTemplate.DocumentTemplateUrl = string.Format("~sitecollection/" + randomList.GetListUrl() + "/Forms/" + templateFileName);
#pragma warning restore 618

                web.AddList(listWithDocumentTemplate);
            });

            TestModel(webModel);
        }
示例#4
0
        public Chunk Generate(ChunkType type, Vector3Int coords, GameObject chunkPrefab)
        {
            Vector3 center = ((Vector3)coords) * chunkSize;
            int     n      = GetRandomAsteroidsCount(type);
            var     b      = new Bounds(center, chunkSize);

            var chunkObj = GameObject.Instantiate(chunkPrefab, center, Quaternion.identity, g.ChunksRoot);
            var chunk    = chunkObj.GetComponent <Chunk>();

            chunk.Init(chunkSize, g, coords);

            for (int i = 0; i < n; i++)
            {
                float   x     = b.PercentX(i, n);
                Vector3 place = b.RandomYZ(x);

                var asteroidType = Rnd.WeightedPick(type.availableTypes);

                var asteroid = AsteroidGenerator.Generate(place, asteroidType, g.AstersRoot);
                chunk.AttachAsteroid(asteroid);
            }

            return(chunk);
        }
示例#5
0
        public void ShouldFail_On_InternalName_MoreThan_32()
        {
            var isValid = false;

            var model = SPMeta2Model.NewSiteModel(site =>
            {
                site.AddRandomField(ct =>
                {
                    (ct.Value as FieldDefinition).InternalName = Rnd.String(33);
                });
            });

            try
            {
                Service.DeployModel(null, model);
            }
            catch (Exception e)
            {
                isValid = e is SPMeta2ModelDeploymentException &&
                          e.InnerException is SPMeta2ModelValidationException;
            }

            Assert.IsTrue(isValid);
        }
示例#6
0
        public void CanDeploy_Web_WithIndexed_Props()
        {
            var webDef = ModelGeneratorService.GetRandomDefinition <WebDefinition>(def =>
            {
                def.IndexedPropertyKeys.Add(new IndexedPropertyValue
                {
                    Name  = string.Format("name_{0}", Rnd.String()),
                    Value = string.Format("value_{0}", Rnd.String()),
                });

                def.IndexedPropertyKeys.Add(new IndexedPropertyValue
                {
                    Name  = string.Format("name_{0}", Rnd.String()),
                    Value = string.Format("value_{0}", Rnd.String()),
                });
            });

            var model = SPMeta2Model.NewWebModel(web =>
            {
                web.AddWeb(webDef);
            });

            TestModel(model);
        }
        public override void Paint(Level level)
        {
            Painter.Rect(level, this, 3, Tile.Chasm);
            Painter.Rect(level, this, 4, Tile.Chasm);

            var c = Rnd.Int(1, 3);
            var d = Rnd.Chance() ? PlatformController.ClockWise : PlatformController.CounterClockWise;

            for (var i = 0; i < c; i++)
            {
                var platform = new MovingPlatform();
                platform.StartingStep = i;

                if (i == 0)
                {
                    platform.Position = new Vector2(Left + 3, Top + 3) * 16;
                }
                else if (i == 2 || (i == 1 && c == 2))                     // For symetry
                {
                    platform.Position     = new Vector2(Right - 4, Bottom - 4) * 16;
                    platform.StartingStep = 2;
                }
                else if (i == 1)
                {
                    platform.Position = new Vector2(Right - 4, Top + 3) * 16;
                }
                else if (i == 3)
                {
                    platform.Position = new Vector2(Left + 3, Bottom - 4) * 16;
                }

                platform.Controller = d;

                level.Area.Add(platform);
            }
        }
示例#8
0
        private string GetCheckCode(HttpContext context)
        {
            string _checkCode = string.Empty;

            if (VCODE_TYPE == Types.Number)
            {
                _checkCode = Rnd.RandomNum(VCODE_LENGTH);
            }
            else
            {
                _checkCode = Rnd.RandomCode(VCODE_LENGTH);
            }

            if (VCODE_IsEncrypt)
            {
                context.Session[VCODE_SESSION] = Os.Brain.Common.Encrypts.MD5.Encode(VCODE_IsIgnore ? _checkCode : _checkCode.ToLower());
            }
            else
            {
                context.Session[VCODE_SESSION] = VCODE_IsIgnore ? _checkCode : _checkCode.ToLower();
            }

            return(_checkCode);
        }
        public void ShouldFail_On_Invalid_AddUniqueContentTypeOrder_ContentTypeId()
        {
            var model = SPMeta2Model.NewWebModel(web =>
            {
                web.AddRandomList(list =>
                {
                    list.AddUniqueContentTypeOrder(new UniqueContentTypeOrderDefinition
                    {
                        ContentTypes = new List <ContentTypeLinkValue>
                        {
                            new ContentTypeLinkValue()
                            {
                                ContentTypeId = Rnd.String()
                            }
                        }
                    });
                });
            });

            WithExceptionValidation(() =>
            {
                Service.DeployModel(null, model);
            });
        }
示例#10
0
        public override string GetString()
        {
            var os = base.GetString().ToCharArray();

            for (int i = 0; i < os.Length; i++)
            {
                var cc = os[i];
                if (cc < 0x4e00 || cc > 0x9fa5)
                {
                    continue;
                }
                if (Rnd.NextDouble() > Rate)
                {
                    continue;
                }
                string s;
                if (!ReplaceDic.TryGetValue(cc, out s))
                {
                    continue;
                }
                os[i] = s[Rnd.Next(1, 300) % s.Length];
            }
            return(string.Join("", os));
        }
示例#11
0
        public override DefinitionBase GenerateRandomDefinition(Action <DefinitionBase> action)
        {
            return(WithEmptyDefinition(def =>
            {
                if (Rnd.Bool())
                {
                    def.QuickLaunchEnabled = null;
                }
                else
                {
                    def.QuickLaunchEnabled = Rnd.Bool();
                }


                if (Rnd.Bool())
                {
                    def.TreeViewEnabled = null;
                }
                else
                {
                    def.TreeViewEnabled = Rnd.Bool();
                }
            }));
        }
示例#12
0
        public void Merge()
        {
            const int  size        = 65536;
            const int  numToMerge  = 5;
            const int  cardinality = 1000;
            const uint expectedCardinalityOfMerged = numToMerge * cardinality;

            var lcs      = new LinearCounter[numToMerge];
            var baseline = new LinearCounter(size);

            for (var i = 0; i < numToMerge; ++i)
            {
                lcs[i] = new LinearCounter(size);
                for (var j = 0; j < cardinality; ++j)
                {
                    int val = Rnd.Next();
                    lcs[i].OfferHashed(Hash32(val));
                    baseline.OfferHashed(Hash32(val));
                }
            }

            ulong  mergeAllEstimate = LinearCounter.MergeAll(lcs).Cardinality();
            double mergeAllError    = Math.Abs((double)mergeAllEstimate - expectedCardinalityOfMerged) / expectedCardinalityOfMerged;

            Assert.That(mergeAllError, Is.EqualTo(0.01).Within(0.01));

            var mergeWithEstimate = lcs[0].MergeWith(lcs.Skip(1).ToArray()).Cardinality();
            var mergeWithError    = Math.Abs((double)mergeWithEstimate - expectedCardinalityOfMerged) / expectedCardinalityOfMerged;

            Assert.That(mergeWithEstimate, Is.EqualTo(mergeAllEstimate));
            Assert.That(mergeWithError, Is.EqualTo(mergeAllError));

            ulong baselineEstimate = baseline.Cardinality();

            Assert.That(mergeWithEstimate, Is.EqualTo(baselineEstimate));
        }
示例#13
0
文件: MazeA.cs 项目: foomow/Maze
        private void Expand(uint[] seeds)
        {
            List <uint> nextSeeds = new List <uint>();

            while (seeds.Length > 0)
            {
                nextSeeds.Clear();
                foreach (uint idx in seeds)
                {
                    uint[] candidates = Explore(idx);
                    if (candidates.Length > 0)
                    {
                        uint newIdx = candidates[Rnd.Next(0, candidates.Length)];
                        Cells[newIdx].Type = CellType.Wall;
                        nextSeeds.Add(newIdx);
                    }
                }
                if (Fun_onExpand != null)
                {
                    Fun_onExpand.Invoke();
                }
                seeds = nextSeeds.Distinct().ToArray();
            }
        }
        public override DefinitionBase GenerateRandomDefinition(Action <DefinitionBase> action)
        {
            return(WithEmptyDefinition(def =>
            {
                def.Title = Rnd.String();
                def.FileName = Rnd.String() + ".html";

                def.Description = Rnd.String();

                var pageIndex = Rnd.Int(2);
                var pages = new[]
                {
                    Encoding.UTF8.GetBytes(DefaultHtmlMasterPageTemplates.DesignManagerStarter)
                };

                def.Content = pages[0];
                def.NeedOverride = true;

                if (Rnd.Bool())
                {
                    def.DefaultCSSFile = string.Format("{0}.css", Rnd.String());
                }
            }));
        }
        public override DefinitionBase GenerateRandomDefinition(Action <DefinitionBase> action)
        {
            return(WithEmptyDefinition(def =>
            {
                // ID must be more than 32 due ScriptEditorWebPart issue
                // it calculated hidden field name as 'this.ID.Substring(this.ID.Length - 36);'
                def.Id = Rnd.String(64);
                def.Title = Rnd.String();

                def.ZoneId = "FullPage";
                def.ZoneIndex = Rnd.Int(100);

                //def.WebpartXmlTemplate = DefaultWebpartTemplates.ContentEditorWebpart;
                def.WebpartFileName = BuiltInWebpartFileNames.MSContentEditor;

                if (Rnd.Bool())
                {
                    def.ExportMode = BuiltInExportMode.All;
                }

                def.Width = Rnd.Int(500);
                def.Height = Rnd.Int(500);
            }));
        }
示例#16
0
        public override double AdjustMouse(int shotNumber)
        {
            double horizontalOffset;
            double verticalOffset;
            int    warmUpShort = this.GetModuleType(4) != WeaponModuleType.Legendary ? 15 : 3;

            if (shotNumber < warmUpShort)
            {
                this.AdjustmentCoefficient = CalculateAdjustment(shotNumber, 20);
                horizontalOffset           = Rnd.NextDouble() * 1 + 1;
                verticalOffset             = Rnd.NextDouble() * (2) + 5;
            }
            else
            {
                this.AdjustmentCoefficient = CalculateAdjustment(shotNumber, 80);
                var hAdj = shotNumber > 25 ? -1.5d : 1.5d;
                horizontalOffset = hAdj * (Rnd.NextDouble() * 0.5 + 1);
                verticalOffset   = Rnd.NextDouble() * 0.5 + 2d;
            }

            this.MoveMouse(horizontalOffset, verticalOffset);

            return(this.GetAdjustmentTime(1d));
        }
        public void CanDeploy_SecurityGroup_Under_SecurityGroup()
        {
            var activeDirectoryOrGlobalO365Groups = RunnerEnvironmentUtils.GetEnvironmentVariable(EnvironmentConsts.DefaultTestADGroups)
                                                    .Split(',');

            var randomNestedGroup = Rnd.RandomFromArray(activeDirectoryOrGlobalO365Groups);

            var spGroup     = ModelGeneratorService.GetRandomDefinition <SecurityGroupDefinition>();
            var domainGroup = ModelGeneratorService.GetRandomDefinition <SecurityGroupDefinition>(def =>
            {
                def.Name = randomNestedGroup;
            });

            var siteModel = SPMeta2Model
                            .NewSiteModel(site =>
            {
                site.AddSecurityGroup(spGroup, group =>
                {
                    group.AddSecurityGroup(domainGroup);
                });
            });

            TestModels(new ModelNode[] { siteModel });
        }
示例#18
0
        /// <summary>
        /// Возвращает -1/intencity*ln(rnd);
        /// </summary>
        /// <param name="intencity"></param>
        /// <param name="realValue">Реальное значение гсч.</param>
        /// <returns></returns>
        public double Next(int intencity, out double realValue)
        {
            int stackMaximum = 0;

            double value;
            double realVal;

            do
            {
                if (stackMaximum > 1000)
                {
                    throw new Exception(
                              "Минмальный интервал: слишком большое значение."
                              );
                }

                realVal = Rnd.NextDouble();
                value   = -Math.Log(realVal) / intencity;
                stackMaximum++;
            }while (value < MinValue);

            realValue = realVal;
            return(value);
        }
示例#19
0
        public override void Update(float dt)
        {
            base.Update(dt);

            lastRay -= dt;

            if (lastRay <= 0)
            {
                lastRay = Math.Max(0.1f, (5f - t) / 20f);
                rays.Add(new Ray {
                    Angle = Rnd.AnglePI()
                });
            }

            GetComponent <LightComponent>().Light.Radius = scale * 2f;

            t  += dt;
            tt += dt;

            if (t > 0.5f)
            {
                angle += (t - 0.5f) * 300 * dt;
                scale += dt * scale;
            }

            if (scale >= 12)
            {
                Done = true;
                OnEnd?.Invoke();
            }

            foreach (var r in rays)
            {
                r.Scale.Y = r.Scale.X = Math.Min(1, r.Scale.X + dt);
            }
        }
示例#20
0
            public override void Init()
            {
                base.Init();
                Quacks++;
                if (Quacks >= 150)
                {
                    Achievements.Unlock("bk:quackers");
                }

                var hat = Self.GetComponent <HatComponent>().Item;

                if (hat != null && (hat.Id == "bk:villager_head" || hat.Id == "bk:stone_hat"))
                {
                    Audio.PlaySfx($"villager{Rnd.Int(1, 5)}", 1f, Rnd.Float(-0.5f, 0.5f));
                }
                else
                {
                    Audio.PlaySfx("quck", 1f, Rnd.Float(-0.5f, 0.5f));
                }

                Self.HandleEvent(new QuackEvent {
                    Player = (Player)Self
                });
            }
        public void SpawnMe()
        {
            try
            {
                if (Die)
                {
                    return;
                }
                lock (Helpers.Manager.clients)
                {
                    for (int i = 0; i < Helpers.Manager.clients.Count; i++)
                    {
                        PlayerMgr sys = Helpers.Manager.clients[i];
                        if (x >= (sys.Character.Position.x - 50) && x <= ((sys.Character.Position.x - 50) + 100) && y >= (sys.Character.Position.y - 50) && y <= ((sys.Character.Position.y - 50) + 100) && Spawned(sys.Character.Information.UniqueID) == false)
                        {
                            Spawn.Add(sys.Character.Information.UniqueID);
                            sys.client.Send(Client.Packet.ObjectSpawn(this));
                        }
                    }
                }

                if (AutoMovement && AutoRun == null)
                {
                    StartRunTimer(Rnd.Next(1, 5) * 1000);
                }

                if (Agresif == 1)
                {
                    StopAgressiveTimer(); StartAgressiveTimer(1000);
                }
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }
        }
示例#22
0
        protected override void PaintRoom(Level level)
        {
            var m = 1;

            Painter.Fill(level, this, Tile.WallA);
            Painter.Fill(level, this, m, Tile.Chasm);

            m += Rnd.Int(0, 2);

            if (Rnd.Chance())
            {
                Painter.FillEllipse(level, this, m, Tiles.RandomFloor());
            }
            else
            {
                Painter.Fill(level, this, m, Tiles.RandomFloor());
            }

            m++;

            if (Rnd.Chance())
            {
                Painter.FillEllipse(level, this, m, Tiles.RandomNewFloor());
            }
            else
            {
                Painter.Fill(level, this, m, Tiles.RandomNewFloor());
            }

            if (Rnd.Chance())
            {
                PaintTunnel(level, Tiles.RandomFloor(), GetCenterRect(), true);
            }

            PaintTunnel(level, Tiles.RandomFloor(), GetCenterRect());
        }
示例#23
0
        protected void AddListWorkflow(WebModelNode web)
        {
            var workflow           = ModelGeneratorService.GetRandomDefinition <SP2013WorkflowDefinition>();
            var workflowEnableList = ModelGeneratorService.GetRandomDefinition <ListDefinition>();

            var historyList = GetHistoryList();
            var taskList    = GetTaskList();

            web

            .AddList(historyList)
            .AddList(taskList)
            .AddList(workflowEnableList, list =>
            {
                list.AddSP2013WorkflowSubscription(new SP2013WorkflowSubscriptionDefinition
                {
                    Name = Rnd.String(),
                    WorkflowDisplayName = workflow.DisplayName,
                    HistoryListUrl      = historyList.GetListUrl(),
                    TaskListUrl         = taskList.GetListUrl()
                });
            })
            .AddSP2013Workflow(workflow);
        }
示例#24
0
            public override void Init()
            {
                base.Init();
                T = 0;

                if (away)
                {
                    target = Self.Center + MathUtils.CreateVector(Self.Target.AngleTo(Self) + Rnd.Float(-1, 1), 96f);
                    delay  = Rnd.Float(1f, 2f);
                    return;
                }

                delay = Rnd.Float(0.3f, 1f);
                var toTarget = Self.Target != null && Rnd.Chance();

                if (toTarget)
                {
                    target = Self.Target.Center;
                }
                else
                {
                    target = Self.GetComponent <RoomComponent>().Room.GetRandomFreeTile();
                }
            }
        public void MergeSelf_ForceNormal_FromChunked()
        {
            int[] cardinalities = { 0, 1, 10, 100, 1000, 10000, 100000, 1000000 };
            foreach (var cardinality in cardinalities)
            {
                for (uint j = 4; j < 24; ++j)
                {
                    Console.WriteLine("p=" + j);
                    var hll = new HyperLogLogPlus(j, 0);
                    for (var l = 0; l < cardinality; l++)
                    {
                        hll.OfferHashed(Hash64(Rnd.Next()));
                    }

                    Console.WriteLine("hllcardinality={0} cardinality={1}", hll.Cardinality(), cardinality);

                    var deserialized = HyperLogLogPlus.FromChunkedByteArray(hll.ToChunkedByteArray());
                    Assert.That(deserialized.Cardinality(), Is.EqualTo(hll.Cardinality()));
                    var merged = hll.Merge(deserialized);
                    Console.WriteLine(merged.Cardinality() + " : " + hll.Cardinality());
                    Assert.That(merged.Cardinality(), Is.EqualTo(hll.Cardinality()));
                }
            }
        }
示例#26
0
        public override void Update(float dt)
        {
            if (!Entity.OnScreen || Variants.Length == 0)
            {
                return;
            }

            if (!Entity.TryGetComponent <DialogComponent>(out var d))
            {
                return;
            }

            if (d.Current != null)
            {
                if (trigger != null && trigger.DistanceToSquared(Entity) > RadiusMax)
                {
                    trigger = null;
                    d.Close();
                }

                return;
            }

            foreach (var p in Entity.Area.Tagged[Tags.Player])
            {
                if (p.DistanceToSquared(Entity) <= Radius && (!UseLineOfSight || CanSee(p.Center, Entity)))
                {
                    if (CanTalk == null || CanTalk(Entity))
                    {
                        d.Start(DecideVariant?.Invoke(p) ?? Variants[Rnd.Int(Variants.Length)]);
                        trigger = p;
                        return;
                    }
                }
            }
        }
示例#27
0
        private void SpiritBladeConsumer(IPlayer player, RoundResult rr)
        {
            if (!SpiritBladeActive)
            {
                return;
            }
            var highroller = Rnd.Next(1, 101);

            if (player.Settings.PrimaryWeaponProc == WeaponProc.BladeOfTheSeventhSon)
            {
                player.AddBonusAttack(rr, new SpiritBlade(player));
                player.AddBonusAttack(rr, new BladeOfTheSeventhSon(player));
                _spiritBladeCharges--;
            }
            if (player.HasPassive("HardenedBlade") && highroller <= 30)
            {
                {
                    if (player.HasPassive("Deluge"))
                    {
                        _deluge += 1;
                    }

                    player.AddBonusAttack(rr, new SpiritBlade(player));
                    return;
                }
            }
            if (player.HasPassive("Deluge"))
            {
                _deluge += 1;
            }
            else
            {
                player.AddBonusAttack(rr, new SpiritBlade(player));
            }
            _spiritBladeCharges--;
        }
示例#28
0
        public WorkflowAssociationDefinitionGenerator()
        {
            WorkflowName = Rnd.String();

            HistoryList = new ListDefinition
            {
                Title        = Rnd.String(),
                Hidden       = true,
                TemplateType = BuiltInListTemplateTypeId.WorkflowHistory,
#pragma warning disable 618
                Url = Rnd.String()
#pragma warning restore 618
            };

            TaskList = new ListDefinition
            {
                Title        = Rnd.String(),
                Hidden       = true,
                TemplateType = BuiltInListTemplateTypeId.Tasks,
#pragma warning disable 618
                Url = Rnd.String()
#pragma warning restore 618
            };
        }
示例#29
0
        public static Projectile Make(Entity owner, string slice, double angle = 0,
                                      float speed = 0, bool circle  = true, int bounce = 0, Projectile parent = null,
                                      float scale = 1, float damage = 1, Item item     = null, float range    = -1)
        {
            if (slice == "default")
            {
                slice = "rect";
            }

            var projectile = new Projectile();

            owner.Area.Add(projectile);

            if (owner is Mob && Rnd.Chance(MobDestrutionChance))
            {
                projectile.Done = true;
                return(projectile);
            }

            projectile.Range = range;

            if (parent != null)
            {
                projectile.Color = parent.Color;
            }
            else if (owner is Player)
            {
                projectile.Color = ProjectileColor.Yellow;
            }

            projectile.Boost        = owner is Player;
            projectile.Damage       = damage;
            projectile.Scale        = scale;
            projectile.Slice        = slice;
            projectile.Parent       = parent;
            projectile.Owner        = owner;
            projectile.StarterOwner = owner;
            projectile.BounceLeft   = bounce;

            var graphics = new ProjectileGraphicsComponent("projectiles", slice);

            projectile.AddComponent(graphics);

            if (graphics.Sprite == null)
            {
                Log.Error($"Not found projectile slice {slice}");
                projectile.Done = true;
                return(projectile);
            }

            owner.HandleEvent(new ProjectileCreatedEvent {
                Owner      = owner,
                Item       = item,
                Projectile = projectile
            });

            scale = projectile.Scale;

            var w = graphics.Sprite.Source.Width * scale;
            var h = graphics.Sprite.Source.Height * scale;

            projectile.Width  = w;
            projectile.Height = h;
            projectile.Center = owner.Center;

            if (owner is Mob m && m.HasPrefix)
            {
                projectile.Scourged = true;
                projectile.Color    = ProjectileColor.Black;
                projectile.AddLight(64, ProjectileColor.Black);
            }

            if (circle)
            {
                projectile.AddComponent(projectile.BodyComponent = new CircleBodyComponent(0, 0, w / 2f, BodyType.Dynamic, false, true));
            }
            else
            {
                projectile.AddComponent(projectile.BodyComponent = new RectBodyComponent(0, 0, w, h, BodyType.Dynamic, false, true));
            }

            projectile.BodyComponent.Body.Restitution = 1;
            projectile.BodyComponent.Body.Friction    = 0;
            projectile.BodyComponent.Body.IsBullet    = true;

            projectile.BodyComponent.Body.Rotation = (float)angle;

            if (owner.TryGetComponent <BuffsComponent>(out var buffs) && buffs.Has <SlowBuff>())
            {
                speed *= 0.5f;
            }

            speed *= 10f;

            if (Math.Abs(speed) > 0.01f)
            {
                projectile.BodyComponent.Velocity =
                    new Vector2((float)(Math.Cos(angle) * speed), (float)(Math.Sin(angle) * speed));
            }

            if (parent != null && parent.TryGetComponent <LightComponent>(out var l))
            {
                projectile.AddLight(l.Light.Radius, l.Light.Color);
            }

            return(projectile);
        }
示例#30
0
        public override void Create(Level level, int x, int y, int z)
        {
            BaseSize = 9 + Rnd.Next(5);

            if (Roots > 0f)
            {
                for (int k = 0; k < 3; k++)
                {
                    GenerateBranch(level, x, y + Roots, z, (120 * k) - 40 + Rnd.Next(80), 1.6f + (float)Rnd.NextDouble() * 0.1f, Roots * 1.7f, 1f,
                                   17, 3);              //17 = Wood, 3 = Jungle Type
                }
            }

            for (int i = y + Roots; i < y + BaseSize; i++)
            {
                Block block = BlockFactory.GetBlockById(17);
                block.Metadata    = 3;
                block.Coordinates = new BlockCoordinates(x, i, z);

                level.SetBlock(block);
            }

            float horDir, verDir;
            int   eX, eY, eZ;

            for (int j = 0; j < Branches; j++)
            {
                horDir = (120 * j) - 60 + Rnd.Next(120);
                verDir = VerticalStart + (float)Rnd.NextDouble() * VerticalRand;

                eX = x + (int)(Math.Cos(horDir * Math.PI / 180D) * verDir * BranchLength);
                eZ = z + (int)(Math.Sin(horDir * Math.PI / 180D) * verDir * BranchLength);
                eY = y + BaseSize + (int)((1f - verDir) * BranchLength);

                GenerateBranch(level, x, y + BaseSize, z, horDir, verDir, BranchLength, 1f,
                               17, 3);          //17 = Wood, 3 = Jungle Type

                for (int m = 0; m < 1; m++)
                {
                    GenerateLeaves(level, eX, eY, eZ, 4f, 1.5f,
                                   18, 3,              //18 = Leaves, 3 = Jungle Type
                                   17, 3);             //17 = Wood, 3 = Jungle Type
                }
            }
        }