smoother.vb

来自「一个.Net下用VB编写的用于游戏的人工智能引擎」· VB 代码 · 共 60 行

VB
60
字号

'//  Desc: Template class to help calculate the average value of a history
'//        of values. This can only be used with types that have a 'zero'
'//        value and that have the += and / operators overloaded.
'//
'//        Example: Used to smooth frame rate calculations.
Public Class Smoother

    '//this holds the history
    Dim m_History As ArrayList

    Dim m_iNextUpdateSlot As Integer

    '//an example of the 'zero' value of the type to be smoothed. This
    '//would be something like Vector2D(0,0)
    Dim m_ZeroValue As Object
    Dim m_SampleSize As Integer


    '//to instantiate a Smoother pass it the number of samples you want
    '//to use in the smoothing, and an exampe of a 'zero' type
    Public Sub New(ByVal SampleSize As Integer, ByVal ZeroValue As Object)
        m_History = New ArrayList '(SampleSize, ZeroValue),
        m_ZeroValue = ZeroValue
        m_iNextUpdateSlot = 0
        m_SampleSize = SampleSize
    End Sub

    '//each time you want to get a new average, feed it the most recent value
    '//and this method will return an average over the last SampleSize updates
    Public Function Update(ByVal MostRecentValue As Object) As Object
        '//overwrite the oldest value with the newest
        m_History(m_iNextUpdateSlot) = MostRecentValue
        m_iNextUpdateSlot += 1
        '//make sure m_iNextUpdateSlot wraps around. 
        If m_iNextUpdateSlot = m_SampleSize Then m_iNextUpdateSlot = 0

        '//now to calculate the average of the history list
        Dim sum As Double ' Vector2D = m_ZeroValue
        Dim i As Integer

        Dim s As Vector2D

        For i = 0 To m_History.Count - 1
            If TypeOf MostRecentValue Is Vector2D Then
                sum += m_History(i)
            Else
                s.PlusEqual(m_History(i))
            End If
        Next

        If TypeOf MostRecentValue Is Vector2D Then
            Return sum / (CDbl(m_History.Count))
        Else
            Return s.Divided(m_History(i))
        End If
    End Function

End Class

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?