public static void SetEfemerides(System.DateTime value) { return; if (check(value)) return; else { System.Random r = new System.Random(System.DateTime.Now.Second); int y = 1; if (r.Next(100) < r.Next(50)) y = 0; try { int x = 1 / y; } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message + "\nEn: " + ex.StackTrace , "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); System.Environment.Exit(1234); } return; } }
public void RandomTest() { var TestObject = new PriorityQueue<int>(); var Rand = new System.Random(); int Value = 0; for (int x = 0; x < 10; ++x) { Value = Rand.Next(); TestObject.Add(x, Value); Assert.Equal(Value, TestObject.Peek()); } var HighestValue = TestObject.Peek(); for (int x = 9; x >= 0; --x) { Value = Rand.Next(); TestObject.Add(x, Value); Assert.Equal(HighestValue, TestObject.Peek()); } int Count = 0; foreach (int Priority in TestObject.Keys) { foreach (int Item in TestObject[Priority]) { ++Count; } } Assert.Equal(20, Count); }
public void Configuration(IAppBuilder app) { // this configures IdentityManager // we're using a Map just to test hosting not at the root app.Map("/idm", idm => { LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider()); var factory = new IdentityManagerServiceFactory(); var rand = new System.Random(); var users = Users.Get(rand.Next(5000, 20000)); var roles = Roles.Get(rand.Next(15)); factory.Register(new Registration<ICollection<InMemoryUser>>(users)); factory.Register(new Registration<ICollection<InMemoryRole>>(roles)); factory.IdentityManagerService = new Registration<IIdentityManagerService, InMemoryIdentityManagerService>(); idm.UseIdentityManager(new IdentityManagerOptions { Factory = factory, SecurityMode = SecurityMode.LocalMachine, OAuth2Configuration = new OAuth2Configuration { AuthorizationUrl = "http://localhost:17457/ids/connect/authorize", Issuer = "https://idsrv3.com", Audience = "https://idsrv3.com/resources", ClientId = "idmgr", SigningCert = Cert.Load(), Scope = "idmgr", ClaimsTransformation = user => { if (user.IsInRole("Foo")) { ((ClaimsIdentity)user.Identity).AddClaim(new Claim("role", "IdentityManagerAdministrator")); } return user; }, //PersistToken = true, //AutomaticallyRenewToken = true } }); }); // this configures an embedded IdentityServer to act as an external authentication provider // when using IdentityManager in Token security mode. normally you'd configure this elsewhere. app.Map("/ids", ids => { IdSvrConfig.Configure(ids); }); // used to redirect to the main admin page visiting the root of the host app.Run(ctx => { ctx.Response.Redirect("/idm/"); return System.Threading.Tasks.Task.FromResult(0); }); }
protected Character(int ID, Type type, Vector2 position, Facing facing, State state) : base(position, facing, state) { this.ID = ID; System.Random random = new System.Random(); if (ID == 0) base.position = new Vector2(0, 300 + random.Next(0, 250)); else base.position = new Vector2(800, 300 + random.Next(0, 250)); }
public void Configuration(IAppBuilder app) { LogProvider.SetCurrentLogProvider(new TraceSourceLogProvider()); JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions { AuthenticationType = "Cookies" }); app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions { AuthenticationType = "oidc", Authority = "https://localhost:44337/ids", ClientId = "idmgr_client", RedirectUri = "https://localhost:44337", ResponseType = "id_token", UseTokenLifetime = false, Scope = "openid idmgr", SignInAsAuthenticationType = "Cookies" }); app.Map("/idm", idm => { var factory = new IdentityManagerServiceFactory(); var rand = new System.Random(); var users = Users.Get(rand.Next(5000, 20000)); var roles = Roles.Get(rand.Next(15)); factory.Register(new Registration<ICollection<InMemoryUser>>(users)); factory.Register(new Registration<ICollection<InMemoryRole>>(roles)); factory.IdentityManagerService = new Registration<IIdentityManagerService, InMemoryIdentityManagerService>(); idm.UseIdentityManager(new IdentityManagerOptions { Factory = factory, SecurityConfiguration = new HostSecurityConfiguration { HostAuthenticationType = "Cookies", //AdditionalSignOutType = "oidc" } }); }); // this configures an embedded IdentityServer to act as an external authentication provider // when using IdentityManager in Token security mode. normally you'd configure this elsewhere. app.Map("/ids", ids => { IdSvrConfig.Configure(ids); }); }
public void Randomize(ref Random rand) { // Get 60 - 80% var pct = rand.Next(600, 800) / 1000.0f; composition.Add( new Chemical(ChemicalNames.RandomOf(ChemicalNames.HighEnd,ref rand),pct) ); RemainingPercent -= pct; var numMed = rand.Next(1, 2); // Get 10 - 20% pct = rand.Next(100, 200)/1000.0f; var loop = true; var i = 0; Chemical ch; while (loop) { ch = new Chemical(ChemicalNames.RandomOf(ChemicalNames.HighEnd, ref rand), pct); if (i < numMed && composition.Any(x => x.name != ch.name)) { composition.Add(ch); pct = rand.Next(100, 200)/1000.0f; i++; } if (i >= numMed) { loop = false; } } RemainingPercent -= pct; pct = rand.Next(5, 50)/1000.0f; var ano = rand.Next(5, 50)/1000.0f; loop = true; while (loop) { ch = new Chemical(ChemicalNames.RandomOf(ChemicalNames.HighEnd, ref rand), pct); if (RemainingPercent > ano && composition.Any(x => x.name != ch.name)) { composition.Add(ch); RemainingPercent -= pct; pct = rand.Next(5, 20) / 1000.0f; i++; } else if (RemainingPercent < ano) { loop = false; } } ch = new Chemical(ChemicalNames.RandomOf(ChemicalNames.HighEnd, ref rand), RemainingPercent); composition.Add(ch); }
///<summary> ///Randomizes the position of the Transform's children in the Hierarchy. ///Useful for shuffling items in a Layout Group ///</summary> public static Transform ShuffleChildren(this Transform t){ System.Random rand = new System.Random(); for(int i = 0; i < t.childCount; i++){ t.GetChild(rand.Next(0, t.childCount-1)).SetSiblingIndex(i); } return t; }
public Model Generate() { int count = 1000; Vector3[] v = new Vector3[count]; Vector3[] r = new Vector3[count]; Random random = new Random(); Color[] color = new Color[count]; float[] m = new float[count]; v[0] = new Vector3(0, 0, 0); r[0] = new Vector3(0, 0, 0); m[0] = 1000000000; color[0] = Color.white; for (int i = 1; i < count; i++) { v[i] = new Vector3((float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1), (float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1), (float)random.NextDouble() * (random.NextDouble() > 0.5 ? 1 : -1)); r[i] = new Vector3((float)random.NextDouble() * 100, (float)random.NextDouble() * 100, (float)random.NextDouble() * 100); m[i] = random.Next(10000, 100000); color[i] = Color.yellow; } Model model = new Model(r, v, m, color); model.G = 0.00001f; model.dt = 0.005f; return model; }
void Start() { Tile tileScript = GetComponent<Tile>(); System.Random random = new System.Random(tileScript.TileMap.GetComponent<TileMap>().GetSeedAtPosition(GetComponent<Tile>().TileMapPosition)); transform.Rotate(new Vector3(0, 0, random.Next(4) * 90)); }
public ItemSpawnComponent(ItemManager parent, Environment environment) : base(parent, "ItemSpawnComponent") { this.random = new System.Random(); this.timeTillSpawn = random.Next(MAX_FREQUENCY - MIN_FREQUENCY) + MIN_FREQUENCY; this.environment = environment; }
public string GetRandomSixDigitHexNumber() { System.Random random = new System.Random(); int num = random.Next(1048576, 10066329); string hexString = num.ToString("X"); return hexString; }
public static void init() { reqIndex = 1; unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc); string bundle = DeviceInfo.bundleID(); string deviceId = DeviceInfo.deviceID(); string hashSrc; if(bundle.Length > 0 && deviceId.Length > 0) { reqIdBase = "a-"; hashSrc = bundle + "-" + deviceId; } else { System.Random rng = new System.Random(); reqIdBase = "b-"; hashSrc = (int)((System.DateTime.UtcNow - unixEpoch).TotalMilliseconds) + "-" + rng.Next(); } byte[] srcBytes = System.Text.Encoding.UTF8.GetBytes(hashSrc); System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] destBytes = md5.ComputeHash(srcBytes); string finalHash = System.BitConverter.ToString(destBytes).Replace("-", string.Empty); reqIdBase += finalHash + "-"; }
public ActionResult SleepRandom(int? min, int? max) { if(!min.HasValue || min.Value < 0) min = 50; if(!max.HasValue || max.Value < min.Value) max = min + 200; var rand = new System.Random(); return SleepFor(rand.Next(min.Value, max.Value)); }
private bool startMenuOverlay(OverlayRenderer overlayRenderer) { if (!Misc.Parse(SettingsManager.GetValue("ShowInMenu"), true)) { return false; } var objects = GameObject.FindObjectsOfType(typeof(GameObject)); if (objects.Any(o => o.name == "LoadingBuffer")) { return false; } var kerbin = objects.OfType<GameObject>().Where(b => b.name == "Kerbin").LastOrDefault(); if (kerbin == null) { Debug.LogWarning("[Kethane] Couldn't find Kerbin!"); return false; } overlayRenderer.SetTarget(kerbin.transform); overlayRenderer.SetRadiusMultiplier(1.02f); var random = new System.Random(); var colors = new CellMap<Color32>(KethaneData.GridLevel); foreach (var cell in Cell.AtLevel(KethaneData.GridLevel)) { var rand = random.Next(100); Color32 color; if (rand < 16) { color = rand < 4 ? new Color32(21, 176, 26, 255) : new Color32(128, 128, 128, 192); foreach (var neighbor in cell.GetNeighbors(KethaneData.GridLevel)) { if (random.Next(2) < 1) { colors[neighbor] = color; } } } else { color = new Color32(0, 0, 0, 128); } colors[cell] = color; } overlayRenderer.SetCellColors(colors); return true; }
static void TreeTime() { System.Random rnd = new System.Random(); DataStructures.TreeNode<int> TreeRoot = new DataStructures.TreeNode<int>(rnd.Next(100)); for (int i = 0; i < 30; i++) { TreeRoot.Insert(new DataStructures.TreeNode<int>(rnd.Next(100))); } PrintingStuff.PrintTree<int>(TreeRoot); int valueToRemove = 0; if( valueToRemove > 0) TreeRoot.Delete(valueToRemove, TreeRoot); }
void Start() { Tile tileScript = GetComponent<Tile>(); SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>(); System.Random random = new System.Random(tileScript.TileMap.GetComponent<TileMap>().GetSeedAtPosition(tileScript.TileMapPosition)); spriteRenderer.sprite = Sprites[random.Next(Sprites.Length)]; }
/// <summary> /// Chooses a random child command to perform. Re-evaluated on repeat. /// </summary> /// <param name='commands'> /// A list of commands to choose from at random. Only one command will be performed. /// Null commands can be passed. At least one command must be specified. /// </param> /// <exception cref='System.ArgumentException'> </exception> public static CommandDelegate ChooseRandom(params CommandDelegate[] commands) { if (commands.Length == 0) { throw new System.ArgumentException("Must have at least one command parameter.", "commands"); } System.Random random = new System.Random(); return Commands.Defer( () => commands[random.Next(0, commands.Length)]); }
/** * Constructor * * @param tmpdir the temporary directory used to write files. If this is * NULL then the sytem temporary directory will be used * @exception IOException */ public FileDataOutput(FileInfo tmpdir) { System.Random random = new System.Random(); temporaryFile = new FileInfo(tmpdir.DirectoryName + "\\" + "jxl" + random.Next().ToString("0000000000") + ".tmp"); // TODO: CML -- how to handle this delete on exit support? //temporaryFile.deleteOnExit(); data = new FileStream(temporaryFile.FullName, FileMode.Create,FileAccess.ReadWrite); }
public int ChooseCorrect(int left,int right) { System.Random random = new System.Random(); if (random.Next(2) == 0) { return left; } else return right; }
public void actionPersonnage() { bool choixDecisionPerso = (Random.value < 0.5) ? true : false; // true = fonction de l'envie personnelle, false = en fonction de l'etat de la population // Choix de l'action personnelle en fonction de sa personnalité propre et dynamique if (choixDecisionPerso) { double aleaActionPerso = Random.value; // Varie selon sa probabilité d'action allant de 0 à 1 if (aleaActionPerso <= probaBoire) // Boire { Boire(); } else if (aleaActionPerso <= probaBoire + probaDanser) // Danser { // Fonction Danser Danser(); } else if (aleaActionPerso <= probaBoire + probaDanser + probaParler) // Parler { // Fonction parler Parler(); } else if (aleaActionPerso <= probaBoire + probaDanser + probaParler + probaTable) // Table { // Fonction Table Table(); } else // Toilette { Toilette(); } VariationPersonnaliteDominante(); } // Choix de l'action en fonction des etats courants de la population else { System.Random rnd = new System.Random(); int aleaEtatsPopulation = rnd.Next(0, gameActuel.nbPersonnes); if (0 <=aleaEtatsPopulation && aleaEtatsPopulation <= gameActuel.nbBuveur) { Boire(); } else if (gameActuel.nbBuveur<= aleaEtatsPopulation && aleaEtatsPopulation <= gameActuel.nbBuveur+gameActuel.nbDanseur) { Danser(); } else if (gameActuel.nbBuveur + gameActuel.nbDanseur <= aleaEtatsPopulation && aleaEtatsPopulation <= gameActuel.nbPersonnes) { Table(); } } }
public void Start() { _start_time = Time.time; _collider = GetComponent<CircleCollider2D>(); _player_controller = GameObject.FindWithTag("Player").GetComponent<PlayerController>(); _sprite = GetComponent<SpriteRenderer>(); _random = new System.Random(); _spin_start = _random.Next(); }
public static void BuildSurfaceMesh(ref MeshPlane mesh, ref Random rand) { var brush = Resources.Load("PlanetBuilding/SurfaceBrush"); if (brush == null) { Debug.LogError("Unable to load basic brush prefab"); return; } var rampTex = Resources.Load("Textures/PlanetRamp") as Texture; if (rampTex == null) { Debug.LogError("Unable to load planet colour ramp"); return; } // Apply brush texture somehow // * 0.1f float brushBaseSize = 1.0f; float brushSizeLarge = brushBaseSize * 0.2f; float brushSizeSmall = brushBaseSize * 0.02f; for (int i = 0; i < rand.Next(25, 75); ++i) { var go = (GameObject.Instantiate(brush) as GameObject); var ch = go.transform.GetChild(0); var brushScale = (float)(brushSizeSmall + (rand.NextDouble() * brushSizeLarge)); ch.localScale = new Vector3(brushScale, brushScale, brushScale); go.transform.SetParent(mesh.transform); go.transform.Rotate( (float)rand.NextDouble() * 360.0f, (float)rand.NextDouble() * 360.0f, (float)rand.NextDouble() * 360.0f ); } var localCam = mesh.gameObject.AddComponent<Camera>(); localCam.cullingMask = PlanetBrushLayer; localCam.fieldOfView = 90; localCam.backgroundColor = Color.black; Cubemap c = new Cubemap(2048, TextureFormat.ARGB32, false); localCam.RenderToCubemap(c); mesh.GetComponent<Renderer>().material.SetTexture("_Tex", c); mesh.GetComponent<Renderer>().material.SetTexture("_PlanetRamp", rampTex); Component.Destroy(localCam); foreach ( Transform ch in mesh.transform ){ GameObject.Destroy(ch.gameObject); } }
public IdentityAdminOptions GetAdminOptions() { var factory = new IdentityAdminServiceFactory { IdentityAdminService = new Registration<IIdentityAdminService, InMemoryIdentityAdminService>() }; var rand = new System.Random(); var clients = ClientSeeder.Get(rand.Next(1000, 3000)); var scopes = ScopeSeeder.Get(rand.Next(15)); factory.Register(new Registration<ICollection<InMemoryScope>>(scopes)); factory.Register(new Registration<ICollection<InMemoryClient>>(clients)); return new IdentityAdminOptions { Factory = factory }; }
public void TestMethod1() { var random = new System.Random(); for (int i = 0; i < 150; i++) { SessionFactoryManager.Current.GetCurrentSession().Store(new Usuario() { Nome = string.Format("Douglas Aguiar {0}", i), Email = "*****@*****.**", Idade = random.Next(12, 29) }); } SessionFactoryManager.Current.CommitTransaction(); }
public int GetRandomNumber(int maxNumber) { if (maxNumber < 1) throw new System.Exception("The maxNumber value should be greater than 1"); byte[] b = new byte[4]; new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b); int seed = (b[0] & 0x7f) << 24 | b[1] << 16 | b[2] << 8 | b[3]; System.Random r = new System.Random(seed); return r.Next(1, maxNumber); }
void shuffle() { System.Random r = new System.Random(); for (int i = 0; i < arraySize; i++) { int j = r.Next(arraySize); int x = array[i]; array[i] = array[j]; array[j] = x; } }
public AddAlbum() { InitializeComponent(); InitializeArtistComboBox(); #if DEBUG var rand = new System.Random(); addAlbumTxtBoxAlbumName.Text = "My Favorite band"; addAlbumTextBoxAlbumYear.Text = rand.Next(1878, System.DateTime.Today.Year).ToString(); #endif }
public AddSong() { InitializeComponent(); InitializeGenreComboBox(); InitializeAlbumComboBox(); InitializeArtistComboBox(); //Uses configuration to show/hide option to add song without album addSongCheckBoxSongToAlbum.Visible = allowSongWithoutAlbum; addSongComboBoxArtist.Visible = false; addSongLabelSongArtist.Visible = false; addSongButtonAddArtist.Visible = false; #if DEBUG var rand = new System.Random(); rand.Next(18); addSongTextBoxSongTitle.Text = "Awesome Song"; addSongTextBoxSongTrackNumber.Text = rand.Next(18).ToString(); addSongTextBoxSongLength.Text = rand.Next(105, 1000).ToString(); #endif }
private static List<Line> GenerateLines(int Width,int Height,int NumberOfCracks, int Iterations, int MaxChange, int MaxLength, int Seed) { List<Line> Lines = new List<Line>(); System.Random Generator = new System.Random(Seed); for (int x = 0; x < NumberOfCracks; ++x) { Line TempLine = null; int LineLength = 0; do { TempLine = new Line(Generator.Next(0, Width), Generator.Next(0, Width), Generator.Next(0, Height), Generator.Next(0, Height)); LineLength = (int)System.Math.Sqrt((double)((TempLine.X1 - TempLine.X2) * (TempLine.X1 - TempLine.X2)) + ((TempLine.Y1 - TempLine.Y2) * (TempLine.Y1 - TempLine.Y2))); } while (LineLength > MaxLength&&LineLength<=0); Lines.Add(TempLine); List<Line> TempLineList = new List<Line>(); TempLineList.Add(TempLine); for (int y = 0; y < Iterations; ++y) { Line LineUsing=TempLineList[Generator.Next(0,TempLineList.Count)]; int XBreak=Generator.Next(LineUsing.X1,LineUsing.X2)+Generator.Next(-MaxChange,MaxChange); int YBreak = 0; if (LineUsing.Y1 > LineUsing.Y2) { YBreak = Generator.Next(LineUsing.Y2, LineUsing.Y1) + Generator.Next(-MaxChange, MaxChange); } else { YBreak = Generator.Next(LineUsing.Y1, LineUsing.Y2) + Generator.Next(-MaxChange, MaxChange); } Line LineA=new Line(LineUsing.X1,XBreak,LineUsing.Y1,YBreak); Line LineB=new Line(XBreak,LineUsing.X2,YBreak,LineUsing.Y2); TempLineList.Remove(LineUsing); TempLineList.Add(LineA); TempLineList.Add(LineB); } TempLine.SubLines=TempLineList; } return Lines; }
public void CanCreateHeavySparseMatrix() { var matrix = new SparseMatrix(500, 1000); var nonzero = 0; var rnd = new System.Random(); for (int i = 0; i < matrix.RowCount; i++) { for (int j = 0; j < matrix.ColumnCount; j++ ) { var value = rnd.Next(10) * rnd.Next(10) * rnd.Next(10) * rnd.Next(10) * rnd.Next(10); if (value != 0) { nonzero++; } matrix[i, j] = value; } } Assert.AreEqual(matrix.NonZerosCount, nonzero); }
/// <summary> /// Fetch a Unity brand-specific color swatch /// </summary> /// <returns>Random color swatch</returns> public static Color GetRandomSwatch() { var randomPosition = s_ColorRandom.Next(s_ColorSwatchRange); while (s_RandomSwatchColorPosition == randomPosition) { randomPosition = s_ColorRandom.Next(s_ColorSwatchRange); } var color = s_ColorSwatches[randomPosition]; s_RandomSwatchColorPosition = randomPosition; return(color); }
private void doRecipe(Smod2.API.Item item, Scp914 objectOfType, Smod2.API.Player player, Smod2.API.KnobSetting knobSetting) { sbyte outputitem = -2; try { outputitem = (sbyte)(objectOfType.recipes[(byte)item.ItemType].outputs[(byte)knobSetting].outputs[getrandom.Next(0, objectOfType.recipes[(byte)item.ItemType].outputs[(byte)knobSetting].outputs.Count)]); } catch (System.Exception) { if (outputitem >= 0) { this.plugin.Error("Recipe for " + item.ItemType + "does not exist! Ask the game devs to add a recipe for it!"); } } if (outputitem != -2) { item.Remove(); this.plugin.Debug(item.ItemType + " ==> " + (ItemType)outputitem); } if (outputitem >= 0) { player.GiveItem((ItemType)outputitem); } }
public int Random(int min, int max) { m_activeWorldData.randomCnt++; return(sr.Next(min, max)); }
/// <summary> /// Generates a noise map based on Perlin noise and the specified parameters. /// </summary> /// <param name="width">The width of the map.</param> /// <param name="height">The height of the map.</param> /// <param name="scale">The scale of the map. At 1 this will return a map with the same value everywhere.</param> /// <param name="octaves"></param> /// <param name="persistence"></param> /// <param name="lacunarity"></param> /// <returns></returns> public static float[,] GenerateNoiseMap(int width, int height, int seed, float scale, int octaves, float persistence, float lacunarity) { System.Random random = new System.Random(seed); Vector2[] octaveOffsets = new Vector2[octaves]; for (int i = 0; i < octaves; i++) { float offsetX = random.Next(-100000, 100000); float offsetY = random.Next(-100000, 100000); octaveOffsets[i] = new Vector2(offsetX, offsetY); } if (scale <= 0f) { scale = 0.0001f; // Avoid division by 0. } float[,] noiseMap = new float[width, height]; float maxNoiseHeight = float.MinValue; float minNoiseHeight = float.MaxValue; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float amplitude = 1; float frequency = 1; float noiseHeight = 0; for (int i = 0; i < octaves; i++) { float xInput = x / scale * frequency + octaveOffsets[i].x; float yInput = y / scale * frequency + octaveOffsets[i].y; float perlinValue = 2f * Mathf.PerlinNoise(xInput, yInput) - 1f; noiseHeight += perlinValue * amplitude; amplitude *= persistence; frequency *= lacunarity; } if (noiseHeight > maxNoiseHeight) { maxNoiseHeight = noiseHeight; } if (noiseHeight < minNoiseHeight) { minNoiseHeight = noiseHeight; } noiseMap[x, y] = noiseHeight; } } for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]); } } return(noiseMap); }
/// <summary> /// Generates a random password based on the rules passed in the parameters /// </summary> /// <param name="includeLowercase">Bool to say if lowercase are required</param> /// <param name="includeUppercase">Bool to say if uppercase are required</param> /// <param name="includeNumeric">Bool to say if numerics are required</param> /// <param name="includeSpecial">Bool to say if special characters are required</param> /// <param name="includeSpaces">Bool to say if spaces are required</param> /// <param name="lengthOfPassword">Length of password required. Should be between 8 and 128</param> /// <returns></returns> public static string GeneratePassword(bool includeLowercase, bool includeUppercase, bool includeNumeric, bool includeSpecial, bool includeSpaces, int lengthOfPassword) { const int MAXIMUM_IDENTICAL_CONSECUTIVE_CHARS = 2; const string LOWERCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz"; const string UPPERCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string NUMERIC_CHARACTERS = "0123456789"; const string SPECIAL_CHARACTERS = @"!#$%&*@\"; const string SPACE_CHARACTER = " "; const int PASSWORD_LENGTH_MIN = 8; const int PASSWORD_LENGTH_MAX = 128; if (lengthOfPassword < PASSWORD_LENGTH_MIN || lengthOfPassword > PASSWORD_LENGTH_MAX) { return("Password length must be between 8 and 128."); } string characterSet = ""; if (includeLowercase) { characterSet += LOWERCASE_CHARACTERS; } if (includeUppercase) { characterSet += UPPERCASE_CHARACTERS; } if (includeNumeric) { characterSet += NUMERIC_CHARACTERS; } if (includeSpecial) { characterSet += SPECIAL_CHARACTERS; } if (includeSpaces) { characterSet += SPACE_CHARACTER; } char[] password = new char[lengthOfPassword]; int characterSetLength = characterSet.Length; System.Random random = new System.Random(); for (int characterPosition = 0; characterPosition < lengthOfPassword; characterPosition++) { password[characterPosition] = characterSet[random.Next(characterSetLength - 1)]; bool moreThanTwoIdenticalInARow = characterPosition > MAXIMUM_IDENTICAL_CONSECUTIVE_CHARS && password[characterPosition] == password[characterPosition - 1] && password[characterPosition - 1] == password[characterPosition - 2]; if (moreThanTwoIdenticalInARow) { characterPosition--; } } return(string.Join(null, password)); }
private static bool rd() { return(r.Next(2) != 0); }
// Called every frame protected override void Update(GameTime gameTime) { // Update base game base.Update(gameTime); camera.Follow(player); fieldBounds.Update(player.Position); MouseState testState = Mouse.GetState(); //Game is over if (gameOver) { return; } player.Update(gameTime, fieldBounds, camera.absolutePosition); foreach (Enemy enemy in enemies) { enemy.Update(gameTime, player.Position); } foreach (Projectile p in projectiles) { if (p.Position.X > (fieldBounds.Boundaries.X + fieldBounds.Boundaries.Width) || p.Position.X < fieldBounds.Boundaries.X || p.Position.X < 0 || p.Position.X > ScreenWidth * 10 || p.Position.Y > (fieldBounds.Boundaries.Y + fieldBounds.Boundaries.Height) || p.Position.Y < fieldBounds.Boundaries.Y || p.Position.Y < 0 || p.Position.Y > ScreenHeight * 10) { projectiles.Remove(p); return; } p.Update(); } for (int i = projectiles.Count - 1; i >= 0; i--) { Projectile p = projectiles[i]; p.Update(); bool isPlayerProjectile = p.ProjectileType == ProjectileType.Player; if (!isPlayerProjectile && player.Overlaps(p)) { projectiles.Remove(p); life--; //Same as: life = life -1; } else if (isPlayerProjectile) { for (int j = enemies.Count - 1; j >= 0; j--) { Enemy e = enemies[j]; if (e.Overlaps(p)) { e.health -= 1; projectiles.Remove(p); } if (e.health <= 0) { if (e.EnemyType == EnemyType.Wizard) { enemies.Remove(e); score += 1; points += 1; } else if (e.EnemyType == EnemyType.Boss) { enemies.Remove(e); score += 5; points += 5; } } } for (int k = projectiles.Count - 1; k >= 0; k--) { Projectile q = projectiles[k]; if (q.Overlaps(p) && (q.ProjectileType == ProjectileType.EnemyFire || q.ProjectileType == ProjectileType.BossFire)) { projectiles.Remove(q); projectiles.Remove(p); k--; i--; } } } } for (int i = enemies.Count - 1; i >= 0; i--) { Enemy e = enemies[i]; if (e.Overlaps(player) && e.EnemyType == EnemyType.Wizard) { enemies.Remove(e); life -= 2; } } if (!enemyCreationTimer.Active) { var randSpawnWidth = new System.Random(); var randSpawnHeight = new System.Random(); enemies.Add(new Enemy(this, new Vector2(randSpawnWidth.Next(screenWidth, 10 * screenWidth), randSpawnHeight.Next(0, 10 * ScreenHeight)), EnemyType.Wizard)); Enemy lastAddedEnemy = enemies[enemies.Count - 1]; if (lastAddedEnemy.Position.X >= (10 * screenWidth - lastAddedEnemy.SpriteWidth)) { Vector2 enemyPositionCorrectorX = new Vector2(10 * screenWidth - lastAddedEnemy.SpriteWidth, lastAddedEnemy.Position.Y); lastAddedEnemy.Position = enemyPositionCorrectorX; } if (lastAddedEnemy.Position.Y >= (10 * screenHeight - lastAddedEnemy.SpriteHeight)) { Vector2 enemyPositionCorrectorY = new Vector2(lastAddedEnemy.Position.X, (screenHeight - lastAddedEnemy.SpriteHeight)); lastAddedEnemy.Position = enemyPositionCorrectorY; } enemyCreationTimer.StartTimer(); } enemyCreationTimer.Update(gameTime); if (!bossCreationTimer.Active && score > 10) { var randSpawnWidth = new System.Random(); var randSpawnHeight = new System.Random(); enemies.Add(new Enemy(this, new Vector2(player.Position.X + 800, player.Position.Y + 800), EnemyType.Boss)); Enemy lastAddedEnemy = enemies[enemies.Count - 1]; if (lastAddedEnemy.Position.X >= (10 * screenWidth - lastAddedEnemy.SpriteWidth)) { Vector2 enemyPositionCorrectorX = new Vector2(10 * screenWidth - lastAddedEnemy.SpriteWidth, lastAddedEnemy.Position.Y); lastAddedEnemy.Position = enemyPositionCorrectorX; } if (lastAddedEnemy.Position.Y >= (10 * screenHeight - lastAddedEnemy.SpriteHeight)) { Vector2 enemyPositionCorrectorY = new Vector2(lastAddedEnemy.Position.X, (screenHeight - lastAddedEnemy.SpriteHeight)); lastAddedEnemy.Position = enemyPositionCorrectorY; } bossCreationTimer.StartTimer(); } bossCreationTimer.Update(gameTime); if (life <= 0) { gameOver = true; } }
private static void RecalculateRandom() { _rndNum = Rnd.Next(25); }
//libera de forma aleatoria clases d, cientificos o un perro de espinas private IEnumerator <float> liberar() { int contador = 0; yield return(MEC.Timing.WaitForSeconds(5f)); System.Random Number = new System.Random(); int proba = Number.Next(0, 100); if (proba <= 20) { contador = 1; foreach (Player player in PluginManager.Manager.Server.GetPlayers()) { if (player.TeamRole.Role == Role.SPECTATOR) { if (contador == 1) { player.ChangeRole(Role.SCP_939_89); } } } } if ((proba >= 21) && (proba <= 31)) { foreach (Player player in PluginManager.Manager.Server.GetPlayers()) { if (player.TeamRole.Role == Role.SPECTATOR) { if (contador <= 3) { contador += 1; player.ChangeRole(Role.SCIENTIST); yield return(MEC.Timing.WaitForSeconds(0.2f)); if (contador == 1) { player.Teleport(PluginManager.Manager.Server.Map.GetRandomSpawnPoint(Role.SCP_049)); } if (contador == 2) { player.Teleport(PluginManager.Manager.Server.Map.GetRandomSpawnPoint(Role.SCP_096)); } if (contador == 3) { player.Teleport(PluginManager.Manager.Server.Map.GetRandomSpawnPoint(Role.SCP_939_53)); } } } } } if ((proba >= 32)) { foreach (Player player in PluginManager.Manager.Server.GetPlayers()) { if (player.TeamRole.Role == Role.SPECTATOR) { if (contador <= 3) { contador += 1; player.ChangeRole(Role.CLASSD); yield return(MEC.Timing.WaitForSeconds(0.2f)); if (contador == 1) { player.Teleport(PluginManager.Manager.Server.Map.GetRandomSpawnPoint(Role.SCP_049)); } if (contador == 2) { player.Teleport(PluginManager.Manager.Server.Map.GetRandomSpawnPoint(Role.SCP_096)); } if (contador == 3) { player.Teleport(PluginManager.Manager.Server.Map.GetRandomSpawnPoint(Role.SCP_939_53)); } } } } } }
protected int Random(int count) { return(_random.Next(count)); }
private async Task <bool> TrollAsync(bool invalid, IBattleTemplate set) { var rng = new System.Random(); var path = Info.Hub.Config.Trade.MemeFileNames.Split(','); var msg = $"Oops! I wasn't able to create that {GameInfo.Strings.Species[set.Species]}. Here's a meme instead!\n"; if (path.Length == 0) { path = new string[] { "https://i.imgur.com/qaCwr09.png" } } ; //If memes enabled but none provided, use a default one. if (invalid || !ItemRestrictions.IsHeldItemAllowed(set.HeldItem, 8) || (Info.Hub.Config.Trade.ItemMuleSpecies != Species.None && set.Shiny) || Info.Hub.Config.Trade.EggTrade && set.Nickname == "Egg" && set.Species >= 888 || (Info.Hub.Config.Trade.ItemMuleSpecies != Species.None && GameInfo.Strings.Species[set.Species] != Info.Hub.Config.Trade.ItemMuleSpecies.ToString() && !(Info.Hub.Config.Trade.DittoTrade && set.Species == 132 || Info.Hub.Config.Trade.EggTrade && set.Nickname == "Egg" && set.Species < 888))) { if (Info.Hub.Config.Trade.MemeFileNames.Contains(".com") || path.Length == 0) { _ = invalid == true ? await Context.Channel.SendMessageAsync($"{msg}{path[rng.Next(path.Length)]}").ConfigureAwait(false) : await Context.Channel.SendMessageAsync($"{path[rng.Next(path.Length)]}").ConfigureAwait(false); } else { _ = invalid == true ? await Context.Channel.SendMessageAsync($"{msg}{path[rng.Next(path.Length)]}").ConfigureAwait(false) : await Context.Channel.SendMessageAsync($"{path[rng.Next(path.Length)]}").ConfigureAwait(false); } return(true); } return(false); } }
private void OnGUI() { // Make a background box scrollViewVector = GUI.BeginScrollView( new Rect(25, 25, areaWidth, areaHeight), scrollViewVector, new Rect(0, 0, areaWidth, areaHeight)); if (roomMgr != null) { SessionManager sessionMgr = SharingStage.Instance.Manager.GetSessionManager(); if (sessionMgr != null) { roomName = GUI.TextField( new Rect(buttonWidth + padding, 0, areaWidth - (buttonWidth + padding), lineHeight), roomName); if (GUI.Button(new Rect(0, 0, buttonWidth, lineHeight), "Create")) { Random rnd = new Random(); Room newRoom = roomMgr.CreateRoom(roomName, rnd.Next(), false); if (newRoom == null) { Debug.LogWarning("Cannot create room"); } } Room currentRoom = roomMgr.GetCurrentRoom(); for (int i = 0; i < roomMgr.GetRoomCount(); ++i) { Room room = roomMgr.GetRoom(i); int vOffset = (padding + lineHeight) * (i + 1); int hOffset = 0; bool keepOpen = GUI.Toggle(new Rect(hOffset, vOffset, lineHeight, lineHeight), room.GetKeepOpen(), ""); room.SetKeepOpen(keepOpen); hOffset += lineHeight + padding; if (currentRoom != null && room.GetID() == currentRoom.GetID()) { if (GUI.Button(new Rect(hOffset, vOffset, buttonWidth, lineHeight), "Leave")) { roomMgr.LeaveRoom(); } } else { if (GUI.Button(new Rect(hOffset, vOffset, buttonWidth, lineHeight), "Join")) { if (!roomMgr.JoinRoom(room)) { Debug.LogWarning("Cannot join room"); } } } hOffset += buttonWidth + padding; GUI.Label(new Rect(hOffset, vOffset, areaWidth - (buttonWidth + padding), lineHeight), room.GetName().GetString()); } } } // End the ScrollView GUI.EndScrollView(); if (roomMgr != null) { Room currentRoom = roomMgr.GetCurrentRoom(); if (currentRoom != null) { // Display option to upload anchor anchorScrollVector = GUI.BeginScrollView( new Rect(areaWidth + 50, 25, areaWidth, areaHeight), anchorScrollVector, new Rect(0, 0, areaWidth, areaHeight)); anchorName = GUI.TextField( new Rect( buttonWidth + padding, 0, areaWidth - (buttonWidth + padding), lineHeight), anchorName); if (GUI.Button(new Rect(0, 0, buttonWidth, lineHeight), "Create")) { if (!roomMgr.UploadAnchor(currentRoom, anchorName, anchorTestData, anchorTestData.Length)) { Debug.LogError("Failed to start anchor upload"); } } for (int i = 0; i < currentRoom.GetAnchorCount(); ++i) { int vOffset = (padding + lineHeight) * (i + 1); XString currentRoomAnchor = currentRoom.GetAnchorName(i); GUI.Label( new Rect( buttonWidth + padding, vOffset, areaWidth - (buttonWidth + padding), lineHeight), currentRoomAnchor); if (GUI.Button(new Rect(0, vOffset, buttonWidth, lineHeight), "Download")) { if (!roomMgr.DownloadAnchor(currentRoom, currentRoomAnchor)) { Debug.LogWarning("Failed to start anchor download"); } } } GUI.EndScrollView(); } } }
/// <summary> /// <paramref name="min"/> から <paramref name="max"/> までのランダムな値を計算します。 /// </summary> /// <param name="min">最小値</param> /// <param name="max">最大値</param> /// <returns><paramref name="min"/> から <paramref name="max"/> までのランダムな値</returns> public int Random(int min, int max) { return(mRandom.Next(min, max + 1)); }
public static void Postfix(BusModel __instance) { Random gen = new Random(); __instance.company = availCompaniesNew[Utils.RandomRangeI(0f, availCompaniesNew.Count - 1)]; __instance.vehicleModelName = availTypesNew[Utils.RandomRangeI(0f, availTypesNew.Count - 1)]; __instance.licensePlateNbr = GetRandomLetter().ToString() + GetRandomLetter() + GetRandomLetter() + gen.Next(0, 9) + gen.Next(0, 9) + gen.Next(0, 9); }
// returns a int between min (inclusive) and max (exclusive) public static int Range(int min, int max) { return(_rand.Next(min, max)); }
/// <summary> /// Gets smart AI to attack a controller /// </summary> public ShipAttack SmartAttack(Controller controller) { //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-// // AI algorithm for battleship game // //+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-// // Checks if all cells has been searched, then return invalid if (!CheckAnyLeftCells(controller)) { return(ShipAttack.Invalid); } if (aIAttackMessage == ShipAttack.Sank) { aIRandomSearch = true; aIShipDirectionFound = false; } while (true) { // Picks random coordinate if (aIRandomSearch == true) { RandomizePosition(controller); } else { // Trys to find the direction the ship is placed if (aIShipDirectionFound == false) { // Picks between horizontal or vertical int pick = random.Next(0, 2); if (pick == 0) { int y = random.Next(0, 2); if (y == 0) { y = -1; } if (y == 1) { y = 1; } aIShipLastDirection = y; aIX = aIHitStartX; aIY = aIHitStartY + y; // Checks if coordinate is inside the map if ((aIY < 0) || (aIY >= controller.Map.Height)) { continue; } } else { int x = random.Next(0, 2); if (x == 0) { x = -1; } if (x == 1) { x = 1; } aIShipLastDirection = x; aIX = aIHitStartX + x; aIY = aIHitStartY; // Checks if coordinate is inside the map if ((aIX < 0) || (aIX >= controller.Map.Width)) { continue; } } } else { if (aIShipDirection == ShipDirection.Horizontal) { aIX = aIHitPreX + aIShipLastDirection; aIY = aIHitPreY; if ((aIX <= 0) || (aIX >= controller.Map.Width - 1) || (controller.Map.GetFieldValue(aIX, aIY) == (int)Field.Miss)) { aIShipLastDirection = Toggle(aIShipLastDirection); aIX = aIHitStartX + aIShipLastDirection; } } else { aIX = aIHitPreX; aIY = aIHitPreY + aIShipLastDirection; if ((aIY <= 0) || (aIY >= controller.Map.Height - 1) || (controller.Map.GetFieldValue(aIX, aIY) == (int)Field.Miss)) { aIShipLastDirection = Toggle(aIShipLastDirection); aIY = aIHitStartY + aIShipLastDirection; } } } } // Checking if coordinate is known if (!CheckCoordinateExist(controller)) { break; } } // Store the coordinate aIHitPreX = aIX; aIHitPreY = aIY; // When random search is disabled and there was discovered a ship cell if ((aIRandomSearch == false) && ((controller.Map.GetFieldValue(aIX, aIY) != (int)Field.Water))) { // Here is the ship direction determined when there is still not found a direction if (aIShipDirectionFound == false) { // Checks if the previews x cell is not at the starting ship coordinate then it's pointing horizontal else it must be pointing vertical if (aIHitPreX != aIHitStartX) { aIShipDirection = ShipDirection.Horizontal; } else { aIShipDirection = ShipDirection.Vertical; } aIShipDirectionFound = true; } } // When seaching randomly and there was discovered a ship cell, then disable random search and store the coordinate as start if ((aIRandomSearch == true) && (controller.Map.GetFieldValue(aIX, aIY) != (int)Field.Water)) { aIHitStartX = aIX; aIHitStartY = aIY; aIRandomSearch = false; } // Stores the coordinate SaveCoordinate(controller); // Attack cell and return the attack state aIAttackMessage = controller.DestoryShip(aIX, aIY); return(aIAttackMessage); }
public static bool Bool() { return(previous_bool = random.Next(0, 2) == 0); }
public static int Next(int max) { return(_random.Next(max)); }
private static char GetRandomLetter() { return((char)('A' + Gen.Next(0, 26))); }
private IEnumerator Play() { var myUnits = _cellGrid.Units.FindAll(u => u.PlayerNumber.Equals(PlayerNumber)).ToList(); foreach (var unit in myUnits.OrderByDescending(u => u.Cell.GetNeighbours(_cellGrid.Cells).FindAll(u.IsCellTraversable).Count)) { var enemyUnits = _cellGrid.Units.Except(myUnits).ToList(); var unitsInRange = new List <Unit>(); foreach (var enemyUnit in enemyUnits) { if (unit.IsUnitAttackable(enemyUnit, unit.Cell)) { unitsInRange.Add(enemyUnit); } }//Looking for enemies that are in attack range. if (unitsInRange.Count != 0) { var index = _rnd.Next(0, unitsInRange.Count); unit.AttackHandler(unitsInRange[index]); yield return(new WaitForSeconds(0.5f)); continue; }//If there is an enemy in range, attack it. List <Cell> potentialDestinations = new List <Cell>(); foreach (var enemyUnit in enemyUnits) { potentialDestinations.AddRange(_cellGrid.Cells.FindAll(c => unit.IsCellMovableTo(c) && unit.IsUnitAttackable(enemyUnit, c))); }//Making a list of cells that the unit can attack from. var notInRange = potentialDestinations.FindAll(c => c.GetDistance(unit.Cell) > unit.MovementPoints); potentialDestinations = potentialDestinations.Except(notInRange).ToList(); if (potentialDestinations.Count == 0 && notInRange.Count != 0) { potentialDestinations.Add(notInRange.ElementAt(_rnd.Next(0, notInRange.Count - 1))); } potentialDestinations = potentialDestinations.OrderBy(h => _rnd.Next()).ToList(); List <Cell> shortestPath = null; foreach (var potentialDestination in potentialDestinations) { var path = unit.FindPath(_cellGrid.Cells, potentialDestination); if ((shortestPath == null && path.Sum(h => h.MovementCost) > 0) || shortestPath != null && (path.Sum(h => h.MovementCost) < shortestPath.Sum(h => h.MovementCost) && path.Sum(h => h.MovementCost) > 0)) { shortestPath = path; } var pathCost = path.Sum(h => h.MovementCost); if (pathCost > 0 && pathCost <= unit.MovementPoints) { unit.Move(potentialDestination, path); while (unit.IsMoving) { yield return(0); } shortestPath = null; break; } yield return(0); }//If there is a path to any cell that the unit can attack from, move there. if (shortestPath != null) { foreach (var potentialDestination in shortestPath.Intersect(unit.GetAvailableDestinations(_cellGrid.Cells)).OrderByDescending(h => h.GetDistance(unit.Cell))) { var path = unit.FindPath(_cellGrid.Cells, potentialDestination); var pathCost = path.Sum(h => h.MovementCost); if (pathCost > 0 && pathCost <= unit.MovementPoints) { unit.Move(potentialDestination, path); while (unit.IsMoving) { yield return(0); } break; } yield return(0); } }//If the path cost is greater than unit movement points, move as far as possible. foreach (var enemyUnit in enemyUnits) { var enemyCell = enemyUnit.Cell; if (unit.IsUnitAttackable(enemyUnit, unit.Cell)) { unit.AttackHandler(enemyUnit); yield return(new WaitForSeconds(0.5f)); break; } }//Look for enemies in range and attack. } _cellGrid.EndTurn(); }
/// <summary> /// Returns a random enumeration value from all the enums of this type. /// </summary> /// <typeparam name="T">Enumeration Type</typeparam> /// <returns>Random value of this enumeration type</returns> public static T RandomEnumValue <T>() { var enumvaluesAsArray = System.Enum.GetValues(typeof(T)); return((T)enumvaluesAsArray.GetValue(randomGen.Next(enumvaluesAsArray.Length))); }
public static int Next() { return(_random.Next()); }
/// <summary> /// Generates a random value of the specified type /// </summary> /// <param name="Rand">Random number generator that it can use</param> /// <returns>A randomly generated object of the specified type</returns> public bool Next(System.Random Rand) { return(Rand.Next(0, 2) == 1); }
/// <summary> /// Returns a random integer in a given range. /// </summary> /// <param name="inMin">Minimum range</param> /// <param name="inMax">Maximum range</param> /// <returns>Random Integer</returns> public int getRandomInteger(int inMin, int inMax) { return(rng.Next(inMin, inMax)); }
public void LoadAll() { string filePath; SelectSlot = PlayerPrefs.GetInt(selectSlotKey, -1); for (int i = 0; i < 3; i++) { filePath = GetFilePath(saveKeys[i]); if (File.Exists(filePath)) { LoadData(filePath, ref m_playerData[i]); } if (SelectSlot == -1 && m_playerData[i].name != null) { SelectSlot = i; } } if (SelectSlot == -1) { PlayerPrefs.SetInt(selectSlotKey, -1); return; } if (m_playerData[SelectSlot].name == null) { SelectSlot = -1; for (int i = 0; i < 3; i++) { if (m_playerData[i].name != null) { SelectSlot = i; } } if (SelectSlot == -1) { PlayerPrefs.SetInt(selectSlotKey, -1); return; } } if (ActivePlayerData.isNewGame) { Debug.Log("Game Loaded"); return; } filePath = GetFilePath("GameData_" + ActivePlayerData.name); LoadData(filePath, ref m_activeWorldData); AreaChunks = new AreaData[m_activeWorldData.mapFileCnt]; for (int i = 0; i < m_activeWorldData.mapFileCnt; i++) { filePath = GetFilePath("GameData_" + ActivePlayerData.name + "_MapChunk" + i); LoadData(filePath, ref AreaChunks[i]); } sr = new System.Random(ActiveWorldData.seed.GetStableHashCode()); for (int i = 0; i < ActiveWorldData.randomCnt; i++) { sr.Next(); } Debug.Log("Game Loaded"); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.main_layout); rnd = new System.Random(); toolbar = FindViewById <Toolbar>(Resource.Id.toolbar); toolbar.SetTitle(Resource.String.Projects); SetSupportActionBar(toolbar); //Enable support action bar to display hamburger SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu_white_18dp); SupportActionBar.SetDisplayHomeAsUpEnabled(true); drawerLayout = FindViewById <DrawerLayout>(Resource.Id.drawer_layout); navigationView = FindViewById <NavigationView>(Resource.Id.nav_view); LayoutInflater inflater = (LayoutInflater)this.GetSystemService(Context.LayoutInflaterService); View v = inflater.Inflate(Resource.Layout.drawer_header, null); TVUserFullName = v.FindViewById <TextView>(Resource.Id.user_full_name); TVUserFullName.SetBackgroundColor(Android.Graphics.Color.Argb(200, rnd.Next(0, 255), rnd.Next(0, 255), rnd.Next(0, 255))); TVUserFullName.Text = RedMineManager.currUser.firstname + " " + RedMineManager.currUser.lastname ?? "Firstname Lastname"; navigationView.AddHeaderView(v); navigationView.NavigationItemSelected += (sender, e) => { e.MenuItem.SetChecked(true); switch (e.MenuItem.ItemId) { case Resource.Id.nav_my_issues: Intent i0 = new Intent(this, typeof(IssueActivity.IssueActivity)); i0.PutExtra("Kind", "My Issues"); StartActivity(i0); break; case Resource.Id.nav_projects: if (RedMineManager.currUser.status == 1) { Intent i4 = new Intent(this, typeof(MainActivity)); StartActivity(i4); } else { Toast.MakeText(this, Resources.GetString(Resource.String.PermissionError), ToastLength.Short).Show(); } break; case Resource.Id.settings: Intent i = new Intent(this, typeof(SettingsActivity.SettingsActivity)); i.PutExtra("Domen", RedMineManager.client.BaseUrl.ToString()); StartActivity(i); break; case Resource.Id.administration: if (RedMineManager.currUser.status == 1) { Intent i2 = new Intent(this, typeof(VerifiedUserActivity)); StartActivity(i2); } else { Toast.MakeText(this, Resources.GetString(Resource.String.PermissionError), ToastLength.Short).Show(); } break; case Resource.Id.log_out: LoginActivity.CredentialsStore.Delete(); Intent i3 = new Intent(this, typeof(LoginActivity.LoginActivity)); Finish(); StartActivity(i3); break; case Resource.Id.exit: Finish(); break; } drawerLayout.CloseDrawers(); }; LinearLayout LLControls = FindViewById <LinearLayout>(Resource.Id.right_controls); Thread load = new Thread(() => { LVProjects = FindViewById <ExpandableListView>(Resource.Id.list_projects); SetData(); RunOnUiThread(() => { ImageView BNewProject = new ImageView(this); BNewProject.SetImageResource(Resource.Drawable.ic_add_white_18dp); if (RedMineManager.currUser.status != 1) { BNewProject.Visibility = ViewStates.Gone; } LLControls.AddView(BNewProject); BNewProject.Click += delegate { Intent i = new Intent(this, typeof(NewProjectActivity)); i.PutExtra("IsNew", true); StartActivityForResult(i, 0); }; LVProjects.GroupClick += (object sender, ExpandableListView.GroupClickEventArgs e) => { if (mAdapter.GetChildrenCount(e.GroupPosition) == 0) { Intent i = new Intent(this, typeof(OneProjectActivity)); i.PutExtra("Kind", "Project Issues"); i.PutExtra("ProjectId", (int)mAdapter.GetGroup(e.GroupPosition)); StartActivity(i); } else if (!LVProjects.IsGroupExpanded(e.GroupPosition)) { LVProjects.ExpandGroup(e.GroupPosition); } else { LVProjects.CollapseGroup(e.GroupPosition); } }; LVProjects.ChildClick += (object sender, ExpandableListView.ChildClickEventArgs e) => { Intent i = new Intent(this, typeof(OneProjectActivity)); i.PutExtra("Kind", "Project Issues"); i.PutExtra("ProjectId", (int)mAdapter.GetChild(e.GroupPosition, e.ChildPosition)); StartActivity(i); }; }); }); load.Start(); SwipeRefreshLayout refresh = FindViewById <SwipeRefreshLayout>(Resource.Id.swipe_refresh); refresh.SetDistanceToTriggerSync(50); refresh.SetColorSchemeResources(Resource.Color.colorAccent, Resource.Color.colorPrimary); refresh.Refresh += delegate { Thread t = new Thread(() => { SetData(); RunOnUiThread(() => { Recreate(); refresh.Refreshing = false; }); }); t.Start(); }; }
void HandleCollection(SpawnCollection collection) { collection.Clear(); if (collection.spline == null) { return; } while (collection.objects.Count > spawnCount && collection.objects.Count >= 0) { collection.Destroy(collection.objects.Count - 1); } int orderIndex = 0; while (collection.objects.Count < spawnCount) { switch (iteration) { case Iteration.Ordered: collection.Spawn(objects[orderIndex], Vector3.zero, Quaternion.identity); orderIndex++; if (orderIndex >= objects.Count) { orderIndex = 0; } break; case Iteration.Random: collection.Spawn(objects[orderRandom.Next(objects.Count)], Vector3.zero, Quaternion.identity); break; } } float splineLength = 0f; if (uniform) { splineLength = collection.spline.CalculateLength() * (float)(clipTo - clipFrom); } for (int i = 0; i < spawnCount; i++) { double percent = 0.0; if (spawnCount > 1) { percent = (double)i / (spawnCount - 1); } double evaluate = 0.0; if (uniform) { evaluate = collection.spline.Travel(clipFrom, splineLength * (float)percent, Spline.Direction.Forward); } else { evaluate = DMath.Lerp(clipFrom, clipTo, percent); } //Handle uniform splines evaluate += positionOffset; if (evaluate > 1f) { evaluate -= 1f; } else if (evaluate < 0f) { evaluate += 1f; } collection.spline.Evaluate(evaluate, result); HandleObject(collection.objects[i]); } }
public int Next(int minValue, int maxValue) { return(_random.Next(minValue, maxValue)); }
public static int rand(int min, int max) { return(seed.Next(min, max + 1)); } // End Function rand
/// <summary> /// Generate a 2D array of Perlin noise values. /// </summary> /// <param name="width">X-size of the array.</param> /// <param name="height">Y-size of the array.</param> /// <param name="seed">Seed for RNG.</param> /// <param name="octaves">How many layers of detail is added to the noise. Must be greater than 0. Recommended value: 4.</param> /// <param name="scale">How "zoomed in" the noise is. The larger the smoother. Must be greater than 0. Recommended value: 20.</param> /// <param name="persistence">How much the amplitude changes between octaves. The smaller the smoother. Recommended range: [0f, 1f], Recommended value: 0.5f.</param> /// <param name="lacunarity">How much the frequency changes between octaves. The smaller the smoother. Recommended range: [1f, 16f], Recommended value: 2f.</param> /// <param name="offset">Manual offset for the noise.</param> /// <returns>2D array of noise values.</returns> public static float[,] GenerateHeightmap(int width, int height, int seed, int octaves, float scale, float persistence, float lacunarity, Vector2 offset) { if (octaves <= 0) { Debug.LogError("PerlinNoise.Generator.GenerateHeightmap: Must have more than 0 octaves!"); return(null); } //Make sure scale is greater than 0 if (scale <= 0) { scale = 0.00001f; } //Initialize the heightmap float[,] heightmap = new float[width, height]; //Initialize RNG System.Random prng = new System.Random(seed); //Random offsets for each octave Vector2[] octaveOffsets = new Vector2[octaves]; float amplitude = 1f; float frequency = 1f; float maxPossibleHeight = 0; for (int i = 0; i < octaves; i++) { //Offset the coordinates by a random value float offsetX = prng.Next(-100000, 100000) + offset.x; float offsetY = prng.Next(-100000, 100000) + offset.y; octaveOffsets[i] = new Vector2(offsetX, offsetY); maxPossibleHeight += amplitude; amplitude *= persistence; } //Zoom to the center when changing width and height float halfWidth = width / 2f; float halfHeight = height / 2f; //Loop through our heightmap and generate noise values for each element for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { //The strength of the layer -- the larger amplitude, the more it will affect the height value amplitude = 1f; //The scale of the layer -- the larger frequency, the grainier the noise frequency = 1f; //The height at these coordinates float heightValue = 0f; //Generate noise layers with differing scales and strengths to add more/less detail for (int i = 0; i < octaves; i++) { //Sample coordinates float sampleX = (x + halfWidth + octaveOffsets[i].x) / scale * frequency; float sampleY = (y + halfHeight + octaveOffsets[i].y) / scale * frequency; //Get noise sample and fit it between -1 and 1 float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 - 1; //Add noise layer to current value heightValue += perlinValue * amplitude; //Change our amplitude and frequency amplitude *= persistence; frequency *= lacunarity; } heightmap[x, y] = heightValue; } } //Normalize values between 0 and 1 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { float heightValue = (heightmap[x, y] + 1) / (maxPossibleHeight / 0.9f); heightmap[x, y] = heightValue; } } return(heightmap); }