【问题标题】:I need my random values to look like they are rolling C#我需要我的随机值看起来像是在滚动 C#
【发布时间】:2016-06-02 11:59:33
【问题描述】:

我有五个骰子标签,我有一个方法 Roll() 可以设置它们的 文本值。在滚动方法发生的那一刻,它只是使数字出现,但我希望它们看起来像是在滚动。

这就是我所拥有的

//Roll() simulates the rolling of this die. 
    public void Roll()
    {
        if (Active) {

            faceValue = random.Next(1, 7);

            label.Text = faceValue.ToString();
        }

    }

Roll() 是从另一个类中调用的,如下所示:

for (int i = 0; i < dice.Length; i++){
            dice[i].Roll();
        }

我的问题是:

我怎样才能让它看起来像是在一组数字中滚动然后停在一个数字上?

【问题讨论】:

  • 假设 Winforms:这种动画需要一个 Timer。
  • Roll 怎么叫?
  • for (int i = 0; i
  • @TheLethalCoder for (int i = 0; i
  • 调用它几次,每次之间都有一个计时器,可能从 100 毫秒开始,一直增加到 500 毫秒。然后,最后一次调用它并将该值设置为最终值

标签: c# random label


【解决方案1】:

试试这个

public async void Roll()
    {
        if (Active)
        {
           for (int i=0;i<20;i++) //Number of rolls before showing final
           {
               await Task.Delay(100);
               label.Text = random.Next(1, 7).ToString();
            }
        }
    } 

【讨论】:

  • 这不会表现出“慢跑”的精神。也许从 100 开始,每次通过时增加 50。
  • 这不起作用。当我在其他类中调用它时出现异常
  • @FirstStep 我得到一个'System.TypeInitializationException'
  • 它是类 Form 的一部分。如果您使用其他类,则必须检查 label.Text 是否可以更改。并且随机是可访问的......
【解决方案2】:

我测试了一点,这在 WPF 中使用 DispatcherTimer 看起来不错:

    DispatcherTimer timer = new DispatcherTimer();
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        timer.Tick += Roll;
        timer.Interval = new TimeSpan(1);

        Random r = new Random();
        timer.Start();
    }

    Random r = new Random();
    public void Roll(object sender, EventArgs e)
    {
        increment++;
        if (increment >= 250)
        {
            timer.Stop();
            increment = 0;
        }
        DiceLabel.Content = r.Next(1, 7).ToString();
        timer.Interval = new TimeSpan(increment*3000);
    }

如果您想要更快或更长时间,您可以使用以下值:

timer.Interval = new TimeSpan(increment*3000);

这里设置显示新号码之间的时间。

在骰子滚动的时间里,你可以玩:

if (increment >= 250)

希望有帮助,玩得开心。

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 2013-07-15
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多