0

C# 的新手很抱歉,如果这很愚蠢。

到目前为止,关于我的骰子,我有以下代码:

Random DiceRandom = new Random();
int DiceThrow = DiceRandom.Next(1, 7);
Console.WriteLine(DiceThrow);
Console.ReadLine();

Console.WriteLine("Player 1 rolled a " + DiceThrow);
Console.ReadLine();

Console.WriteLine("Player 2 rolled a " + DiceThrow);
Console.ReadLine();

Console.WriteLine("Player 3 rolled a " + DiceThrow);
Console.ReadLine();

Console.WriteLine("Player 4 rolled a " + DiceThrow);
Console.ReadLine();

现在,这会创建一个很好的数字并显示它,但是对于每个玩家来说它都是相同的数字。

我需要一个循环来为每个玩家重复滚动,如果玩家滚动 6,它将再次滚动。

4

3 回答 3

2

怎么样:

for( int player = 1; player <= 4; player++ )
{
    while(1) {
        int DiceThrow = DiceRandom.Next(1, 7);
        Console.WriteLine( "Player " + player + " rolled a " + DiceThrow );
        if( DiceThrow < 6 ) break;
    }
    Console.ReadLine();
}
于 2012-12-10T02:17:11.607 回答
0

不是 100% 确定 readlines 等。但本质上,您每次打印时都会引用相同的掷骰子。您需要做的是每次生成一个新掷骰(通过 DiceRandom.Next(1,7))。

Random DiceRandom = new Random();

for (int i = 1; i <= 4; i++) {
    var roll = DiceRandom.Next(1,7);
    Console.WriteLine("Player 1 rolled a " + roll);
} 
于 2012-12-10T02:16:25.070 回答
0

正如其他人指出的那样,问题在于DiceThrow每次使用时都不会刷新随机数。您可以在不使用循环的情况下解决此问题,但不要。您确实需要一个循环,并且可能看起来像这样:

for(int i = 1; i <= 4; i++) {
    DiceThrow = DiceRandom.Next(1,7);
    Console.WriteLine("Player " + i + " rolled a " + DiceThrow);
    Console.ReadLine();
    if(DiceThrow == 6) i--;
}

The last line is a little obscure, but is there to provide the "reroll on 6" requirement. Since the loop increments i each time, decrementing it will effectively make the loop go around for the same player again.

EDIT: Actually, a more explicit version of this using a while loop instead would be as follows:

int i = 1;
while(i <= 4) {
    DiceThrow = DiceRandom.Next(1,7);
    Console.WriteLine("Player " + i + " rolled a " + DiceThrow);
    Console.ReadLine();
    if(DiceThrow != 6) i++;
}
于 2012-12-10T02:17:29.953 回答