Konami Code in C#

后端 未结 11 2130
执笔经年
执笔经年 2020-12-07 19:07

I am looking to have a C# application implement the Konami Code to display an Easter Egg. http://en.wikipedia.org/wiki/Konami_Code

What is the best way to do this?<

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 19:58

    I know it's an old question, but I embarked on this same journey in VB. I created a class for it:

    Public Class Konami
        ' Here is the pattern to match
        Property KonamiOrder As List(Of Keys) = New List(Of Keys) From {Keys.Up, Keys.Up, Keys.Down, Keys.Down, Keys.Left, Keys.Right, Keys.Left, Keys.Right, Keys.B, Keys.A}
    
        ' Just calling these out ahead of time
        Property sequence As List(Of Boolean)
        Property ix As Integer = 0
    
        ' Hey new object, better set the important bits
        Public Sub New()
            me.reset()
        End Sub
    
        ' Reset on pattern failure, or completion
        Public Function reset() As Boolean
            Me.sequence = New List(Of Boolean) From {False, False, False, False, False, False, False, False, False, False}
            ix = 0
    
        End Function
    
    
        ' Here's where all the action happens
        Public Function checkKey(keycode As Keys)
            'Check to see what they pressed
            If sequence(ix) = False And keycode = KonamiOrder(ix) Then
                ' Hurray, they pressed the right key, better keep track of it
                sequence(ix) = True
                ix += 1
            Else
                ' Nope, reset
                Me.reset()
            End If
    
            'Is the code complete and correct?
            If sequence.Contains(False) Then
                ' Nope, send back failure
                Return False
            Else
                'Yep, reset so it can be used again and send back a success
                Me.reset()
                Return True
            End If
        End Function
    End Class
    

    This is just a sample form's code behind on the usage of the konami class.

    Public Class Form1
        Private oKonami As New Konami
    
        Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
            ' Send the Key press on its way, and get some logic going
            If oKonami.checkKey(e.KeyCode) Then
                ' Congrats, pattern match
                MsgBox("Konami Code Entered")
            End If
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
            ' This will intercept the key events on this form
            Me.KeyPreview = True
        End Sub
    End Class
    

    https://github.com/the1337moderator/KonamiCodeforVB.net

提交回复
热议问题