你好,我对C#和编码很陌生,所以需要一些基本的帮助。如果用户选择掷多个骰子(2,3,4,5,6,7,8等),你怎么做才能让它在所有骰子上随机掷骰子?例如:"骰子滚动:2,5,3"。而不是现在的"骰子滚动:2,2,2"或"4,4,4",而是相同的数字。
static int RollTheDice(Random rndObject)
{
Random dice = new Random();
int nr = dice.Next(1, 7); // if user requests to roll multiple dices how
// do you make all the rolls random and not the same
return nr;
}
static void Main()
{
Random rnd = new Random();
List<int> dices = new List<int>();
Console.WriteLine("ntWelcome to the dicegenerator!");
bool go = true;
while (go)
{
Console.WriteLine("nt[1] Roll the dicen" +
"t[2] Look what you rolledn" +
"t[3] Exit");
Console.Write("tChoose: ");
int chose;
int.TryParse(Console.ReadLine(), out chose);
switch (chose)
{
case 1:
Console.Write("ntHow many dices do you want to roll?: ");
bool input = int.TryParse(Console.ReadLine(), out int antal);
if (input)
{
for (int i = 0; i < antal; i++)
{
dices.Add(RollTheDice(rnd));
}
}
break;
case 2:
Console.WriteLine("ntDices rolled: ");
foreach (int dice in dices)
{
Console.WriteLine("t" + dice);
}
break;
case 3:
Console.WriteLine("ntThank you for rolling the dice!");
Thread.Sleep(1000);
go = false;
break;
default:
Console.WriteLine("ntChoose between 1-3 in the menu.");
break;
您每次都会创建一个新Random
,如果在短时间内调用,它将产生类似的数字。参考这里: 如何在 C# 中生成随机整数?
您已经将Random
传递给您的函数,请使用它而不是创建一个新函数!
static int RollTheDice(Random rndObject)
{
int nr = rndObject.Next(1, 7); // if user requests to roll multiple dices how
// do you make all the rolls random and not the same
return nr;
}