0

我对 c# 很陌生,我正在尝试创建一个沙盒类型的游戏,我使用随机数来选择块去哪里,但我的块总是相同的,因为它总是选择相同的“随机数”。这是我的代码:

    int x = 0; 

    public GameWindow() 
    {
        InitializeComponent();
        Blocks();
    }

    private void BlockThree()
    {

    }

    private void BlockTwo()
    {
        x = 2;
        BlockData();
    }

    private void BlockOne()
    {
        x = 1;
        BlockData();
    }

    private async void Blocks()
    {
        await Task.Delay(5000);
        BlockOne();
        await Task.Delay(5000);
        BlockTwo();
        await Task.Delay(5000);
        BlockThree();
    }

    private async void BlockData()
    {
        Random rand = new Random();

        int num = rand.Next(1, 2);

        if (num == 1)
        {
            if (x == 1)
            {
                pictureBox1.Image = Image.FromFile("C:/Program Files (x86)/SandBoxEngine/grass_side.png");
            }
            else
            {
                if (x == 2)
                {
                    pictureBox2.Image = Image.FromFile("C:/Program Files (x86)/SandBoxEngine/grass_side.png");
                }
            }
        }
        else
        {
            if (num == 2)
            {
                if (x == 1)
                {
                    pictureBox1.Image = Image.FromFile("C:/Program Files (x86)/SandBoxEngine/dirt.png");
                }
                else
                {
                    if (x == 2)
                    {
                        pictureBox2.Image = Image.FromFile("C:/Program Files (x86)/SandBoxEngine/dirt.png");
                    }
                }
            }
        }   
    }
}
4

1 回答 1

3

您需要将 Random 指定为全局。

    private Random rand = new Random();

然后使用 rand.Next

    rand.Next(1,2);

将始终返回 1。获得 1 或 2 使用此。

    rand.Next(1,3);
于 2013-11-09T19:48:12.730 回答