如何按数字顺序排列随机骰子面(Yahtzee)

本文关键字:Yahtzee 随机 何按 数字 顺序 排列 | 更新日期: 2023-09-27 18:36:50

所以我一直在研究yahtzee游戏,到目前为止,我已经得到了随机显示骰子图像的标签,这就是代码。

#region Declaration
Image[] diceImages;
int[] dice;
Random rand;
#endregion
#region Initialization
public Form1()
{
    InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
    diceImages=new Image[7];
    diceImages[0] = Properties.Resources.dice_face_0;
    diceImages[1] = Properties.Resources.dice_face_1;
    diceImages[2] = Properties.Resources.dice_face_2;
    diceImages[3] = Properties.Resources.dice_face_3;
    diceImages[4] = Properties.Resources.dice_face_4;
    diceImages[5] = Properties.Resources.dice_face_5;
    diceImages[6] = Properties.Resources.dice_face_6;
    dice = new int[5] { 0, 0, 0, 0, 0 };
    rand = new Random();
}
#endregion
private void btnRoll_Click(object sender, EventArgs e)
{
    for (int i = 0; i < dice.Length; i++)
        dice[i] = rand.Next(1, 7);
    lblDie1.Image = diceImages[dice[0]];
    lblDie2.Image = diceImages[dice[1]];
    lblDie3.Image = diceImages[dice[2]];
    lblDie4.Image = diceImages[dice[3]];
    lblDie5.Image = diceImages[dice[4]];
}

我可以按数字顺序排列骰子图像吗,如果是,如何排列?

如何按数字顺序排列随机骰子面(Yahtzee)

您可以使用

Array.Sort(MSDN 文档)

private void btnRoll_Click(object sender, EventArgs e)
{
    for (int i = 0; i < dice.Length; i++)
        dice[i] = rand.Next(1, 7);
    Array.Sort(dice);
    lblDie1.Image = diceImages[dice[0]];
    lblDie2.Image = diceImages[dice[1]];
    lblDie3.Image = diceImages[dice[2]];
    lblDie4.Image = diceImages[dice[3]];
    lblDie5.Image = diceImages[dice[4]];
}

完成以下操作后:

for (int i = 0; i < dice.Length; i++)
    dice[i] = rand.Next(1, 7);

创建有序列表:

dice = dice.OrderBy(x => x).ToArray();

,然后继续分配图像。