本文整理汇总了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);
}
示例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);
}
}
}
示例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);
}
示例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();
}
示例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;
}
示例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;
}
示例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());
}
}
}
示例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);
}
}
示例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);
}
}
示例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();
}
}
示例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();
}
示例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;
}
示例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);
}
示例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]
}
};
}
示例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.");
}
}