当前位置: 首页>>代码示例>>C#>>正文


C# Random.Next方法代码示例

本文整理汇总了C#中System.Random.Next方法的典型用法代码示例。如果您正苦于以下问题:C# Random.Next方法的具体用法?C# Random.Next怎么用?C# Random.Next使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Random的用法示例。


在下文中一共展示了Random.Next方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RectangleEnigmaPanel

        /// <summary>
        /// Constructeur par défaut, génère plusieurs carrés.
        /// </summary>
        public RectangleEnigmaPanel()
        {
            Random rnd = new Random();

            TableLayoutPanel centerLayout = new TableLayoutPanel();
            centerLayout.ColumnCount = 27;
            for (int i = 0; i < 27 ;i++)
            {
                centerLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,0.04f));
            }
            centerLayout.RowCount = 21;
            for (int i = 0; i < 21; i++)
            {
                centerLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 0.05f));
            }
            centerLayout.Dock = DockStyle.Fill;
            Controls.Add(centerLayout);

            for (int i = 0; i < tpnlCarre.Length; i++)
            {
                tpnlCarre[i] = new Panel();
                Random randonGen = new Random();
                Color randomColor = Color.FromArgb(randonGen.Next(240), randonGen.Next(240),
                randonGen.Next(255));
                tpnlCarre[i].BackColor = randomColor;
                tpnlCarre[i].Size = new Size(20, 20);
                int iLocX = rnd.Next(1, 27);
                int iLocY = rnd.Next(0, 21);
                centerLayout.Controls.Add(tpnlCarre[i], iLocX, iLocY);
                tpnlCarre[i].Click += new EventHandler(ClickOnCarre);
            }

            centerLayout.Click += new EventHandler(ClickOnPanel);
        }
开发者ID:RomainCapo,项目名称:enigmos,代码行数:37,代码来源:RectangleEnigmaPanel.cs

示例2: ApplySetPieces

        public static void ApplySetPieces(World world)
        {
            var map = world.Map;
            int w = map.Width, h = map.Height;

            Random rand = new Random();
            HashSet<Rect> rects = new HashSet<Rect>();
            foreach (var dat in setPieces)
            {
                int size = dat.Item1.Size;
                int count = rand.Next(dat.Item2, dat.Item3);
                for (int i = 0; i < count; i++)
                {
                    IntPoint pt = new IntPoint();
                    Rect rect;

                    int max = 50;
                    do
                    {
                        pt.X = rand.Next(0, w);
                        pt.Y = rand.Next(0, h);
                        rect = new Rect() { x = pt.X, y = pt.Y, w = size, h = size };
                        max--;
                    } while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 ||
                             rects.Any(_ => Rect.Intersects(rect, _))) &&
                             max > 0);
                    if (max <= 0) continue;
                    dat.Item1.RenderSetPiece(world, pt);
                    rects.Add(rect);
                }
            }
        }
开发者ID:BlackRayquaza,项目名称:MMOE,代码行数:32,代码来源:SetPieces.cs

示例3: Initialise

		public void Initialise()
		{
			_primitives = new List<Cube>();
			var random = new Random();
			for (int i = 0; i < Constants.CubeCount; i++)
			{
				_primitives.Add(new Cube
					{
						Color = Color.Red,
						Position = new Vector3(random.Next(100) - 50, random.Next(100) - 50, -random.Next(100)),
						Radius = random.Next(100),
						Rotation = Vector3.Zero
					});
			}
            //How to create a kernel and a channel?
//			_kernel = 
//		    _channel = 

			

			_colour = Color.Beige;
			
			_kernel.Factory.NewCoroutine(ChangePosition);
			_kernel.Factory.NewCoroutine(ChangeColour);
		    
		}
开发者ID:maconbot,项目名称:c4g,代码行数:26,代码来源:World.cs

示例4: Main

        static void Main(string[] args)
        {
            var m_Config = new ServerConfig
            {
                Port = 911,
                Ip = "Any",
                MaxConnectionNumber = 1000,
                Mode = SocketMode.Tcp,
                Name = "CustomProtocolServer"
            };

            var m_Server = new CustomProtocolServer();
            m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
            m_Server.Start();

            EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);

            using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Connect(serverAddress);

                var socketStream = new NetworkStream(socket);
                var reader = new StreamReader(socketStream, Encoding.ASCII, false);

                string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty)
                    + Guid.NewGuid().ToString().Replace("-", string.Empty);

                Random rd = new Random();

                var watch = Stopwatch.StartNew();
                for (int i = 0; i < 10; i++)
                {
                    int startPos = rd.Next(0, charSource.Length - 2);
                    int endPos = rd.Next(startPos + 1, charSource.Length - 1);

                    var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);

                    byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
                    socketStream.Write(requestNameData, 0, requestNameData.Length);
                    var data = Encoding.ASCII.GetBytes(currentMessage);
                    socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
                    socketStream.Write(data, 0, data.Length);
                    socketStream.Flush();

                   // Console.WriteLine("Sent: " + currentMessage);

                    var line = reader.ReadLine();
                    //Console.WriteLine("Received: " + line);
                    //Assert.AreEqual(currentMessage, line);
                }

                

                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
            }

            Console.ReadLine();
        }
开发者ID:zesus19,项目名称:c5.v1,代码行数:60,代码来源:Program.cs

示例5: GetPen

 public Pen GetPen()
 {
     Random r = new Random();
     Color color = Color.FromArgb(255, r.Next(255), r.Next(255), r.Next(255));
     Pen pen = new Pen(color);
     return pen;
 }
开发者ID:isen131,项目名称:Rectangles,代码行数:7,代码来源:Form1.cs

示例6: GetReady

		public void GetReady ()
		{
			dataTable = new DataTable ("itemTable");
			dc1 = new DataColumn ("itemId");
			dc2 = new DataColumn ("itemName");
			dc3 = new DataColumn ("itemPrice");
			dc4 = new DataColumn ("itemCategory");
			
			dataTable.Columns.Add (dc1);
			dataTable.Columns.Add (dc2);
			dataTable.Columns.Add (dc3);
			dataTable.Columns.Add (dc4);
			DataRow dr;
			seed = 123;
			rowCount = 5;
			rndm = new Random (seed);
			for (int i = 1; i <= rowCount; i++) {
				dr = dataTable.NewRow ();
				dr["itemId"] = "item " + i;
				dr["itemName"] = "name " + rndm.Next ();
				dr["itemPrice"] = "Rs. " + (rndm.Next () % 1000);
				dr["itemCategory"] = "Cat " + ((rndm.Next () % 10) + 1);
				dataTable.Rows.Add (dr);
			}
			dataTable.AcceptChanges ();
			dataView = new DataView (dataTable);
			dataView.ListChanged += new ListChangedEventHandler (OnListChanged);
			listChangedArgs = null;
		}
开发者ID:Profit0004,项目名称:mono,代码行数:29,代码来源:DataViewTest.cs

示例7: ChangeMatchDates

        /// <summary>
        /// If there is no real life data between seasons,
        /// change some match dates to around now for testing purposes
        /// </summary>
        private static void ChangeMatchDates(TtcDbContext context)
        {
            bool endOfSeason = !context.Matches.Any(match => match.Date > DateTime.Now);
            if (true || endOfSeason)
            {
                var passedMatches = context.Matches
                    .Where(x => x.FrenoySeason == Constants.FrenoySeason)
                    //.Where(x => x.Date < DateTime.Today)
                    .OrderByDescending(x => x.Date)
                    .Take(42);

                var timeToAdd = DateTime.Today - passedMatches.First().Date;
                foreach (var match in passedMatches.Take(20))
                {
                    match.Date = match.Date.Add(timeToAdd);
                }

                var rnd = new Random();
                foreach (var match in passedMatches.Take(20))
                {
                    match.Date = DateTime.Today.Add(TimeSpan.FromDays(rnd.Next(1, 20))).AddHours(rnd.Next(10, 20));
                    match.Description = "";
                    match.AwayScore = null;
                    match.HomeScore = null;
                    //match.IsSyncedWithFrenoy = true;
                    match.WalkOver = false;

                    context.MatchComments.RemoveRange(match.Comments.ToArray());
                    context.MatchGames.RemoveRange(match.Games.ToArray());
                    context.MatchPlayers.RemoveRange(match.Players.ToArray());
                }
            }
        }
开发者ID:TTCErembodegem,项目名称:TTC-React-Back,代码行数:37,代码来源:Program.cs

示例8: Main

        static void Main(string[] args)
        {
            const int NumberOfAnimals = 10;
            Stack<Animal> animalStack = new Stack<Animal>();
            Queue<Animal> animalQueue = new Queue<Animal>();

            Console.WriteLine("/// ORDER OF ENTRY...");
            Random r = new Random();
            for (int index = 0; index < NumberOfAnimals; index++)
            {
                var animalShouldBeCat = (r.Next(2) == 0);
                uint nextWeight = (uint)r.Next(10, 40);
                Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave"));
                animalStack.Push(nextAnimal);
                animalQueue.Enqueue(nextAnimal);
                Console.WriteLine(nextAnimal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM STACK...");
            foreach (Animal animal in animalStack)
            {
                Console.WriteLine(animal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM QUEUE...");
            foreach (Animal animal in animalQueue)
            {
                Console.WriteLine(animal);
            }
        }
开发者ID:JackMorris,项目名称:LCS3,代码行数:32,代码来源:Program.cs

示例9: RandomDatagramTest

        public void RandomDatagramTest()
        {
            Random random = new Random();

            for (int i = 0; i != 1000; ++i)
            {
                Datagram datagram = random.NextDatagram(random.Next(1024));

                Assert.AreEqual(datagram, new Datagram(new List<byte>(datagram).ToArray()));
                Assert.AreEqual(datagram.GetHashCode(), new Datagram(new List<byte>(datagram).ToArray()).GetHashCode());

                Assert.AreNotEqual(datagram, random.NextDatagram(random.Next(10 * 1024)));
                Assert.AreNotEqual(datagram.GetHashCode(), random.NextDatagram(random.Next(10 * 1024)).GetHashCode());

                if (datagram.Length != 0)
                {
                    Assert.AreNotEqual(datagram, Datagram.Empty);
                    Assert.AreNotEqual(datagram, random.NextDatagram(datagram.Length));
                    if (datagram.Length > 2)
                        Assert.AreNotEqual(datagram.GetHashCode(), random.NextDatagram(datagram.Length).GetHashCode());
                }
                else
                    Assert.AreEqual(datagram, Datagram.Empty);

                // Check Enumerable
                IEnumerable enumerable = datagram;
                int offset = 0;
                foreach (byte b in enumerable)
                    Assert.AreEqual(datagram[offset++], b);
            }
        }
开发者ID:preyea,项目名称:Pcap.Net,代码行数:31,代码来源:DatagramTests.cs

示例10: RowColOperation

        /// <summary>
        /// Submatrix expression operations
        /// </summary>
        private void RowColOperation()
        {
            Mat src = Cv2.ImRead(FilePath.Image.Lenna);

            Random rand = new Random();
            for (int i = 0; i < 200; i++)
            {
                int c1 = rand.Next(100, 400);
                int c2 = rand.Next(100, 400);
                Mat temp = src.Row[c1];
                src.Row[c1] = src.Row[c2];
                src.Row[c2] = temp;
            }

            src.Col[0, 50] = ~src.Col[450, 500];
            
            // set constant value (not recommended)
            src.Row[450,460] = src.Row[450,460] * 0 + new Scalar(0,0,255);
            // recommended way
            //src.RowRange(450, 460).SetTo(new Scalar(0, 0, 255));

            using (new Window("RowColOperation", src))
            {
                Cv2.WaitKey();
            }
        }
开发者ID:0sv,项目名称:opencvsharp,代码行数:29,代码来源:MatOperations.cs

示例11: Arrange

        protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = TimeSpan.FromSeconds(30);
            _encoding = Encoding.UTF8;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
            _channelMock.InSequence(_sequence).Setup(p => p.Open());
            _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);

            _subsystemSession = new SubsystemSessionStub(
                _sessionMock.Object,
                _subsystemName,
                _operationTimeout,
                _encoding);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }
开发者ID:delfinof,项目名称:ssh.net,代码行数:29,代码来源:SubsystemSession_OnChannelDataReceived_Connected.cs

示例12: GetRandomLong

 public static long GetRandomLong()
 {
     var random = new Random();
     var value = ((long)random.Next()) << 32 + random.Next();
     var sign = random.Next(0, 2) == 0 ? -1 : 1;
     return value * sign;
 }
开发者ID:kurtkilgor,项目名称:Bignum,代码行数:7,代码来源:BasicNaturalTest.cs

示例13: Update

        public override void Update(GameTime gameTime, TeeEngine engine)
        {
            Hero player = (Hero) engine.GetEntity("Player");
            KeyboardState keyboardState = Keyboard.GetState();

            if (KeyboardExtensions.GetKeyDownState(keyboardState, Keys.S, this, true)
                && Entity.IntersectsWith(this, "interaction", player, "Shadow", gameTime))
            {
                if (CurrentDrawableState != "Open")
                {
                    Random random = new Random();

                    _openSfx[random.Next(1)].Play();

                    CurrentDrawableState = "Open";
                    Drawables.ResetState("Open", gameTime);

                    for (int i = 0; i < 10; i++)
                    {
                        Coin coin = new Coin(this.Pos.X, this.Pos.Y, 100, (CoinType)random.Next(3));
                        coin.Pos.X += (float) ((random.NextDouble() - 0.5) * 100);
                        coin.Pos.Y += (float) ((random.NextDouble() - 0.5) * 100);
                        coin.TerrainCollisionEnabled = false;       // Prevent from getting stuck in sorrounding walls.

                        engine.AddEntity(coin);
                    }
                }
            }

            base.Update(gameTime, engine);
        }
开发者ID:MichaelAquilina,项目名称:Some-2D-RPG,代码行数:31,代码来源:Chest.cs

示例14: Next

 internal Address Next(Random r)
 {
     var pref = addresses.prefecture[r.Next(addresses.prefecture.Count)];
     var city = addresses.city[r.Next(addresses.city.Count)];
     var town = addresses.town[r.Next(addresses.town.Count)];
     return new Address
     {
         Prefecture = new JapaneseText
         {
             Kanji = pref[KanjiIndex],
             Hiragana = pref[HiraganaIndex],
             Katakana = pref[KatakanaIndex]
         },
         City = new JapaneseText
         {
             Kanji = city[KanjiIndex],
             Hiragana = city[HiraganaIndex],
             Katakana = city[KatakanaIndex]
         },
         Town = new JapaneseText
         {
             Kanji = town[KanjiIndex],
             Hiragana = town[HiraganaIndex],
             Katakana = town[KatakanaIndex]
         }
     };
 }
开发者ID:yskatsumata,项目名称:dot-gimei,代码行数:27,代码来源:Addresses.cs

示例15: TestSave

        public void TestSave()
        {
            var random = new Random();
            // test saving and reloading
            var list = new List<TestCompositeClass>();
            for (var x = 0; x < 100; x++)
            {
                var testClass = new TestCompositeClass
                {
                    Key1 = random.Next(),
                    Key2 = random.Next().ToString(),
                    Key3 = Guid.NewGuid(),
                    Key4 = DateTime.Now.AddMinutes(-1 * random.Next(100)),
                    Data = Guid.NewGuid().ToString()
                };
                list.Add(testClass);
                _databaseInstance.SaveAsync( testClass ).Wait();
            }

            for (var x = 0; x < 100; x++)
            {
                var actual = _databaseInstance.LoadAsync<TestCompositeClass>( new TestCompositeKeyClass( list[ x ].Key1,
                    list[x].Key2,list[x].Key3,list[x].Key4)).Result;
                Assert.IsNotNull(actual, "Load failed.");
                Assert.AreEqual(list[x].Data, actual.Data, "Load failed: data mismatch.");
            }
        }
开发者ID:blinds52,项目名称:SterlingDB,代码行数:27,代码来源:TestCompositeKeyWithKeyClass.cs


注:本文中的System.Random.Next方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。