用于VB.Net中任何侧面骰子的骰子滚轮

时间:2014-10-23 07:05:34

标签: .net vb.net random dice

我想创建一个骰子滚轮,以便用户可以选择骰子上的多个边,它会随机响应,我的当前代码会一直丢掉相同的数字。

Sub rollDie(ByVal sides As Integer)
    Dim rand As Single = Rnd()
    For cnt As Integer = 1 To sides
        If rand < cnt / sides Then
            diceRoll = cnt
            Exit For
        End If
    Next
    Console.WriteLine("You rolled a {0} sided die which landed on {1}", sides, diceRoll)
End Sub

3 个答案:

答案 0 :(得分:2)

我认为你最好将所有的Die逻辑放入一个类中,然后使用System.Random类为你生成随机数:

Public Class Die
    Private _sides As Integer
    Private Shared _generator As New System.Random '<<<one PRNG no matter how many dice

    Public ReadOnly Property Sides As Integer
        Get
            Return _sides
        End Get
    End Property

    Public Sub New(sides As Integer)
        _sides = sides
    End Sub

    ''' <summary>
    ''' Returns a random number between 1 and the number of sides of the die
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Roll() As Integer
        Return _generator.Next(1, _sides + 1)
    End Function
End Class

然后你可以像这样使用它:

Dim elevensidedDie As New Die(11)
Debug.WriteLine("You rolled a(n) {0} sided die which landed on {1}", elevensidedDie.Sides, elevensidedDie.Roll)

答案 1 :(得分:1)

您应该使用VB.Net的Randomize function为随机数生成器播种,即

Sub rollDie(ByVal sides As Integer)
Randomize()
Dim rand As Single = Rnd()
For cnt As Integer = 1 To sides
    If rand < cnt / sides Then
        diceRoll = cnt
        Exit For
    End If
Next
Console.WriteLine("You rolled a {0} sided die which landed on {1}", sides, diceRoll)
End Sub

Randomize函数使用种子的系统计时器。您可以在程序开头或rollDie函数中将调用发送给它。

答案 2 :(得分:0)

使用循环是生成随机整数的非常低效的方法。请查看this页面以获取更好的方法。

以下是带有评论的最相关位的副本:

' Initialize the random-number generator.
Randomize()
' Generate random value between 1 and 6. 
Dim value As Integer = CInt(Int((6 * Rnd()) + 1))

更简洁,更快捷。