public static void CollectFinalState() { if (WorldProperties.CollectMemesSuccess > .5f) { foreach (var liveMeme in new HashSet <Meme>(tribes.SelectMany(tribe => tribe.AllMemes()))) { if (randomizer.Chance(WorldProperties.ChanceToCollectMemesSuccess)) { liveMeme.ReportDetaliedStatistic(); } } } }
void LightTweenCompleted(ITween <Vector2> tween) { // get a random point on screen and a random delay for the tweens var target = new Vector2(Random.Range(50, SceneRenderTargetSize.X - 100), Random.Range(50, SceneRenderTargetSize.Y - 100)); var delay = Random.Range(0f, 1f); var transform = tween.GetTargetObject() as Transform; tween.PrepareForReuse(transform.Position, target, 2f) .SetCompletionHandler(LightTweenCompleted) .SetDelay(delay) .Start(); // every so often add a scale tween if (Random.Chance(60)) { transform.TweenLocalScaleTo(transform.LocalScale.X * 2f, 1f) .SetLoops(LoopType.PingPong) .SetEaseType(EaseType.CubicIn) .SetDelay(delay) .Start(); } // every so often change our color if (Random.Chance(80)) { var sprite = transform.Entity.GetComponent <SpriteRenderer>(); PropertyTweens.ColorPropertyTo(sprite, "Color", Random.NextColor(), 2f) .SetDelay(delay) .Start(); } }
void AddSpriteLight(Texture2D texture, Vector2 position, float scale) { // random target to tween towards that is on screen var target = new Vector2(Random.Range(50, SceneRenderTargetSize.X - 100), Random.Range(50, SceneRenderTargetSize.Y - 100)); var entity = CreateEntity("light"); var sprite = entity.AddComponent(new SpriteRenderer(texture)); entity.Position = position; entity.Scale = new Vector2(scale); sprite.RenderLayer = SpriteLightRenderLayer; if (Random.Chance(50)) { sprite.SetColor(Random.NextColor()); var cyler = entity.AddComponent(new ColorCycler()); cyler.WaveFunction = (WaveFunctions)Random.Range(0, 5); cyler.Offset = Random.NextFloat(); cyler.Frequency = Random.Range(0.6f, 1.5f); cyler.Phase = Random.NextFloat(); } else { entity.TweenPositionTo(target, 2) .SetCompletionHandler(LightTweenCompleted) .SetRecycleTween(false) .Start(); } }
protected virtual void GenerateRidge(Ridge ridge, Area area, EcsManager ecs, Random random) { var landscape = ecs.GetContainer <Landscape>(); var building = ecs.GetContainer <Building>(); var delta = ridge.To - ridge.From; for (var px = Math.Max(0, Math.Min(ridge.From.X, ridge.To.X) - ridge.Width); px < Math.Min(area.Size.X - 1, Math.Max(ridge.From.X, ridge.To.X) + ridge.Width); px++) { for (var py = Math.Max(0, Math.Min(ridge.From.Y, ridge.To.Y) - ridge.Width); py < Math.Min(area.Size.Y - 1, Math.Max(ridge.From.Y, ridge.To.Y) + ridge.Width); py++) { var position = new Vector(px, py); var internalPosition = delta.TransitionMatrix() * (2 * position - ridge.From - ridge.To).ToMatrix() / 2; var x = internalPosition[0, 0]; var y = internalPosition[1, 0] * delta.Magnitude / ridge.Width * 2; if (random.Chance( 2 * (1 - Math.Sqrt(x * x + y * y)))) { area.ContainerSlice <Landscape>()[position] = landscape.Plain; area.ContainerSlice <Building>()[position] = building.Mountain; } } } }
public void Generate(Area area, EcsManager ecs, Random random) { var landscape = ecs.GetContainer <Landscape>(); var landscapeSlice = area.ContainerSlice <Landscape>(); var maximalLandNumber = LandFraction * area.Size.X * area.Size.Y; var counter = 0; while (counter < maximalLandNumber - 1) { var radius = random.NextDouble() * Math.Sqrt((maximalLandNumber - counter) / Math.PI) / 2; var sourcePosition = random.NextPosition(area.Size); var sizeVector = (int)radius * Vector.One; foreach (var vector in (sizeVector * 2 + Vector.One).Range().Select(v => v - sizeVector)) { var part = (vector.Magnitude - SeasideBorder * radius) / (radius * (1 - SeasideBorder)); if (random.Chance(0.5 * (Math.Abs(part - 1) - Math.Abs(part) + 1))) { var newPosition = Vector.Clamp( vector + sourcePosition, Vector.Zero, area.Size - Vector.One); if (landscapeSlice[newPosition] < landscape.Water) { counter++; landscapeSlice[newPosition] = landscape.Plain; } } } } }
public void PunishFreeRider() { _punishers.Clear(); for (int i = 0; i < members.Count; i++) { var man = members[i]; var chance = man.GetFeature(AvailableFeatures.FreeRiderPunishmentLikelyhood); if (randomizer.Chance(chance)) { _punishers.Add(man); } } if (_punishers.Count > 0) { _freeraidersFeatures.Clear(); double min = double.MaxValue, max = double.MinValue; for (int i = 0; i < members.Count; i++) { double feature = members[i].GetFeature(AvailableFeatures.LikelyhoodOfNotBeingAFreeRider); min = Math.Min(min, feature); max = Math.Max(max, feature); _freeraidersFeatures.Add(feature); } double threshold = min + (max - min) * 0.25; _freeRaiders.Clear(); for (int i = 0; i < _freeraidersFeatures.Count; i++) { if (_freeraidersFeatures[i] > threshold) { _freeRaiders.Add(members[i]); } } if (_freeRaiders.Count > 0) // Такая шизовая ситуация возможна если у всех в племени строго одинаковый геном по данному признаку. { for (int i = 0; i < _punishers.Count; i++) { _punishers[i].DetermineAndPunishAFreeRider(members, _freeRaiders); } } } }
public Tribe(int randomSeed) { id = nextFreeId++; // Племена создаются только из майнтрэда randomizer = new Random(seed = randomSeed); TribeName = NamesGenerator.GenerateTribeName(); keepsLog = randomizer.Chance(WorldProperties.ChancesThatTribeWillWriteALog); yearBegun = World.Year; lastYearActive = yearBegun; if (keepsLog) { logFileName = Path.Combine(World.TribesLogFolder, TribeName + "(" + World.Year); File.WriteAllText(logFileName, Properties.Resources.TribeViewerTemplateBeginning); } }
public override void Begin() { _context.SpriteAnimator.Play("idle"); _context.Mover.Velocity = new Vector2(-1 * Squid.Speed, 0); _context.SpriteAnimator.Color = _context.GetColor(); if (Random.Chance(100)) { new Timer(5, false, () => _machine.ChangeState <SquidTeleState>()); } else { new Timer(5, false, () => _machine.ChangeState <SquidLaserState>()); } }
public void Generate(Area area, EcsManager ecs, Random random) { var landscape = ecs.GetContainer <Landscape>(); var building = ecs.GetContainer <Building>(); foreach (var vector in area.Size.Range()) { if (area.ContainerSlice <Landscape>()[vector] < landscape.Plain && random.Chance( MaximalChance * (1 - 2 / (MaximalTemperature - MinimalTemperature) * Math.Abs(area.GetTemperature(vector) + MinimalTemperature)))) { area.ContainerSlice <Building>()[vector] = building.Forest; } } }
public static Meme InventNewMeme(int seed, AvailableFeatures memeAffectedFeature, List <Meme> memesAlreadyKnown = null) { Meme meme = new Meme(memeAffectedFeature, CreateMemeId(memeAffectedFeature, seed)); var randomizer = new Random(meme.MemeId); meme.yearInvented = World.Year; FeatureDescription featureDescription = WorldProperties.FeatureDescriptions[(int)memeAffectedFeature]; meme.keepDiary = randomizer.Chance(WorldProperties.ChancesThatMemeWillWriteALog); meme.efficiency = -1; meme.price = -1; if (featureDescription.MemeEfficiencyMean > 1 && (featureDescription.range == FeatureRange.ZeroToOne || featureDescription.range == FeatureRange.MinusOneToPlusOne)) { meme.efficiency = 1; } else if (featureDescription.MemeEfficiencyMean <= -1 && featureDescription.range == FeatureRange.MinusOneToPlusOne) { meme.efficiency = -1; } else { do { meme.efficiency = randomizer.NormalRandom(featureDescription.MemeEfficiencyMean, featureDescription.MemeEfficiencyStdDev); if (meme.efficiency == 0) { Console.WriteLine($"meme.efficiency == 0"); } }while (meme.efficiency < featureDescription.LowerRange || (meme.efficiency > featureDescription.UpperRange)); // А что, все мымы теперь 0-1? Может у нас специальный мем снижающий какое-то качество, почему бы и нет, собственно? Пусть отбор решает. Заодно посмотрим что он там нарешать сможет. } meme.complexityCoefficient = Math.Pow(2, (meme.efficiency - featureDescription.MemeEfficiencyMean) / featureDescription.MemeEfficiencyStdDev); // Зачем вообще complexityCoefficient считать внутри цикла? while (meme.price < 0) { var pedestalPrice = featureDescription.MemePricePedestal; var efficiencyPrice = Math.Abs(meme.efficiency) * featureDescription.MemePriceEfficiencyRatio; var randomPricePart = randomizer.NormalRandom(featureDescription.MemePriceRandomMean, featureDescription.MemePriceRandomStdDev); var complexityMultiplier = Math.Pow(meme.ComplexityCoefficient, WorldProperties.MemeCostComplexityPriceCoefficient); meme.price = (pedestalPrice + efficiencyPrice + randomPricePart) * complexityMultiplier; } meme.Report(string.Format("Meme teaches how {3}. It affects: {0}; Efficiency: {1:f5}; It takes {2:f2} memory.", memeAffectedFeature.GetDescription(), meme.Efficiency, meme.Price, meme.ActionDescription)); // Логер, конечно, можно не переделывать, потому что мемы создаются шибко редко. return(meme); }
public void Generate() { cells.Fill(Cell.GROUND); int r = cells.sizeX / 2 - 1; int centerX = cells.sizeX / 2; int centerY = cells.sizeY / 2; for (int y = 0; y < cells.sizeY; ++y) { for (int x = 0; x < cells.sizeX; ++x) { float dsq = Mathf.Sq(x - centerX) + Mathf.Sq(y - centerY); float k = (float)dsq / (float)(r * r); float trunkChance = 0.1f + k * k * k * k; if (Random.Chance(trunkChance)) { cells[x, y] = Cell.TRUNK; } } } mapRenderer.RecalculateTiles(cells); mapCollider.RecalculateCollisionMap(cells); }
/// <summary> /// Generates a random logical filename based on the given directory /// </summary> /// <param name="base">The directory to sample for generation</param> public static FileInfo Generate(DirectoryInfo @base) { if (@base.Exists == false) //for nonexisting { @base.EnsureDirectoryExists(); return(Generate(@base)); //create and retry } DirectoryInfo[] dirs; FileInfo[] files; try { dirs = @base.GetDirectories(); files = @base.GetFiles(); } catch (UnauthorizedAccessException) { return(null); } if (@base.Root.FullName.Equals(@base.FullName)) //is root dir (c:/) { var fn = winfilenames.TakeRandomNonExisting(@base); return(new FileInfo(Path.Combine(@base.FullName, fn))); } if (files.Length == 0 | dirs.Length == 0 && files.Length == 0) //for empty directory //take the directory name and parse it into a file { var realbase = @base; _invalidname: var fn = @base.Name.ToLower().RemoveNumber().Trim('.', ',').Trim(); var spaces = fn.Count(c => c == ' '); if (spaces >= 3) { var splet = fn.Split(' '); fn = rand.Chance(50, splet.Skip(1), splet.Reverse().Skip(1).Reverse()) .StringJoin(rand.Chance(50, "-", "")); fn = fn.DeleteDuplicateCharsMultiple("-"); } else { fn = rand.Chance(50, () => fn.Replace(" ", "-"), () => fn); } if (string.IsNullOrEmpty(fn)) { @base = @base.Parent; goto _invalidname; } return(new FileInfo(Path.Combine(realbase.FullName, fn + rand.CoinToss(rand.CoinToss("-") + RandomVersion()) + datastorageextensions.TakeRandom()))); } //file with number in its end if (files.Where(f => f.HasExtension() && blacklisted_extension.Any(ext => ext.Equals(f.Extension)) == false).Where(f => !string.IsNullOrEmpty(f.GetFileNameWithoutExtension())).Any(f => char.IsDigit(f.GetFileNameWithoutExtension().Reverse().First()))) { var potent = files.Where(f => f.HasExtension() && blacklisted_extension.Any(ext => ext.Equals(f.Extension)) == false).Where(f => !string.IsNullOrEmpty(f.GetFileNameWithoutExtension()) && char.IsDigit(f.GetFileNameWithoutExtension().Reverse().First())).OrderBy(f => f.LastAccessTimeUtc).FirstOrDefault(); //get least touched file with number at end. if (potent != null) { var n = potent.GetFileNameWithoutExtension() .Reverse() .TakeWhile(char.IsDigit) .ToArray() .Take(10) .Reverse() .StringJoin("") .ToDecimal(); bool tried = false; var filewonum = potent.GetFileNameWithoutExtension().Replace(n.ToString(), ""); _retry: if (tried | n < 1 | new Random().CoinToss()) { n++; } else { n--; } tried = true; var t = new FileInfo(Path.Combine(@base.FullName, filewonum + n + potent.Extension)); if (t.Exists) { goto _retry; } return(t); } } //based on file with all lowcase letters and extension var potential = files.Where(f => f.GetFileNameWithoutExtension().All(c => char.IsLetter(c) && char.IsLower(c))).OrderBy(f => f.Extension == ".exe").ThenByDescending(f => f.LastAccessTimeUtc).FirstOrDefault(); if (potential != null) { var favext = FavoriteExtension(files, blacklisted_extension.Concat(potential.Extension.ToEnumerable()).ToArray()); return(potential.ChangeExtension(favext)); } else { potential = files.OrderBy(f => f.Extension == ".exe").ThenByDescending(f => f.LastAccessTimeUtc).FirstOrDefault(); var favext = FavoriteExtension(files, blacklisted_extension.Concat(potential.Extension.ToEnumerable()).ToArray()); return(potential.ChangeExtension(favext)); } }
public SandBox(int width, int height, int scale) : base(width, height, scale) { Name = "Sandbox Simulation"; LeftPlace = SOLID; //define colours ColorMapping.Add(SAND, Color.Yellow); ColorMapping.Add(SOLID, Color.Gray); ColorMapping.Add(WATER, Color.Blue); ColorMapping.Add(ICE, Color.LightSkyBlue); ColorMapping.Add(SMOKE, Color.LightGray); //define callbacks ActionMapping.Add(SAND, (x, y) => { if (Read(x, y + 1) != NULL) { if (Read(x, y + 1) == WATER) { Write(x, y + 1, SAND); Write(x, y, WATER); return; } if (Random.Chance(0.5f)) { if (Read(x + 1, y + 1) == NULL) { //prevent clipping through diagonals if (Read(x + 1, y) == NULL) { //move right down Write(x + 1, y + 1, Read(x, y)); Write(x, y, NULL); } } } else { if (Read(x - 1, y + 1) == NULL) { //prevent clipping through diagonals if (Read(x - 1, y) == NULL) { //move left down Write(x - 1, y + 1, Read(x, y)); Write(x, y, NULL); } } } } else { //move downwards Write(x, y + 1, Read(x, y)); Write(x, y, NULL); } }); ActionMapping.Add(ICE, (x, y) => { if (Read(x, y + 1) != NULL) { if (Read(x, y + 1) == WATER) { Write(x, y + 1, ICE); Write(x, y, ICE); return; } if (Random.Chance(0.5f)) { if (Read(x + 1, y + 1) == NULL) { //prevent clipping through diagonals if (Read(x + 1, y) == NULL) { //move right down Write(x + 1, y + 1, Read(x, y)); Write(x, y, NULL); } } } else { if (Read(x - 1, y + 1) == NULL) { //prevent clipping through diagonals if (Read(x - 1, y) == NULL) { //move left down Write(x - 1, y + 1, Read(x, y)); Write(x, y, NULL); } } } } else { //move downwards Write(x, y + 1, Read(x, y)); Write(x, y, NULL); } }); ActionMapping.Add(WATER, (x, y) => { if (Read(x, y + 1) != NULL) { if (Read(x + 1, y + 1) == NULL) { //prevent clipping through diagonals if (Read(x + 1, y) == NULL) { //move right down Write(x + 1, y + 1, Read(x, y)); Write(x, y, NULL); } } else { if (Random.Chance(0.5f)) { if (Read(x + 1, y) == NULL) { //move right Write(x + 1, y, Read(x, y)); Write(x, y, NULL); } } else { if (Read(x - 1, y) == NULL) { //move left Write(x - 1, y, Read(x, y)); Write(x, y, NULL); } } } } else { //move downwards Write(x, y + 1, Read(x, y)); Write(x, y, NULL); } }); ActionMapping.Add(SMOKE, (x, y) => { if (Read(x, y - 1) != NULL) { if (Random.Chance(0.5f)) { if (Read(x + 1, y) == NULL) { //move right Write(x + 1, y, Read(x, y)); Write(x, y, NULL); } } else { if (Read(x - 1, y) == NULL) { //move left Write(x - 1, y, Read(x, y)); Write(x, y, NULL); } } } else { //move up Write(x, y - 1, Read(x, y)); Write(x, y, NULL); } }); FillBorder(SOLID); }
internal static Texture2D Generate(int width, int height, int clouds) { var texture = new Texture2D(GameInstance.GraphicsDevice, width, height); var data = new Color[texture.Width * texture.Height]; var levelDefinitions = new int[] { (int)(texture.Height * 0.7f), (int)(texture.Height * 0.6f), (int)(texture.Height * 0.5f), (int)(texture.Height * 0.4f) }; var levels = (int[])levelDefinitions.Clone(); var targetLevels = (int[])levelDefinitions.Clone(); for (var x = 0; x < texture.Width; x++) { for (var i = 0; i < levels.Length; i++) { if (levels[i] == targetLevels[i]) { if (x >= width * 0.8f) { targetLevels[i] = levelDefinitions[i]; } else { if (_random.Chance(2)) { if (x > texture.Width / 2) { targetLevels[i] = _random.Next(-2, 6) + levels[i]; } else { targetLevels[i] = _random.Next(-5, 3) + levels[i]; } } } } if (levels[i] < targetLevels[i] && _random.Chance(3)) { levels[i]++; } if (levels[i] > targetLevels[i] && _random.Chance(3)) { levels[i]--; } } for (var y = 0; y < texture.Height; y++) { var index = x + y * texture.Width; if (y < levels[3]) { data[index] = Color.Black; } else if (y < levels[2]) { if (!(x % 2 == 0 && y % 2 == 0)) { data[index] = Color.Black; } } else if (y < levels[1] && (x + (y % 2)) % 2 == 0) { data[index] = Color.Black; } else if (y < levels[0] && x % 2 == 0 && y % 2 == 0) { data[index] = Color.Black; } else { data[index] = Color.Transparent; } } } for (var i = 0; i < clouds; i++) { var cloudWidth = _random.Next(20, 50); var cloudHeight = 0; var posX = _random.Next(0, width - cloudWidth); var posY = _random.Next(10, (int)(height * 0.7f)); var startY = 0; for (var x = 0; x < cloudWidth; x++) { if (x > cloudWidth / 2) { if (_random.Chance(3)) { cloudHeight--; } if (_random.Chance(3)) { startY++; } } else { if (_random.Chance(2)) { cloudHeight++; } if (_random.Chance(2)) { startY--; } } if (startY < 0) { startY = 0; } for (var y = 0; y < cloudHeight; y++) { var destY = startY + posY + y; var destX = posX + x; var index = destX + destY * texture.Width; if (posY < levels[2]) { if (!(destX % 2 == 0 && destY % 2 == 0)) { data[index] = Color.Black; } else { data[index] = Color.Transparent; } } else if (posY < levels[1]) { if ((destX + (destY % 2)) % 2 == 0) { data[index] = Color.Black; } else { data[index] = Color.Transparent; } } else if (posY < levels[0]) { if (x % 2 == 0 && y % 2 == 0) { data[index] = Color.Black; } else { data[index] = Color.Transparent; } } } } } texture.SetData(data); return(texture); }